Struts2中的文件上传和文件下载

来源:互联网 发布:vs code php开发环境 编辑:程序博客网 时间:2024/05/12 14:47

Struts2中的文件上传与下载1)上传文件:1,在WEB-INF/lib下加入 commons-fileupload.jar 和 commons-io.jar2,把form标签的enctype属性设置为:multipart/form-data、method属性设为:post 且form中提供input的type属性是file类型的文件上传域eg:<form action="${pageContext.request.contextPath}/xxx.action" method="post" enctype="multipart/form-data"><input type="file" name="uploadStuff"></form>3,在Action类中添加以下属性。// 单文件上传public class MyAction extends BaseAction implements Serializable {private File uploadStuff;// 封装上传的文件,Struts2会封装成File类型private String uploadStuffFileName;// 封装上传文件的名称private String uploadStuffContentType;// 封装上传文件的类型// 此处省略了getter和setter的方法public String upload() throws Exception{// 处理实际的上传代码//找到存储文件的真实路径String storePath = ServletActionContext.getServletContext().getRealPath(/files);// 方法一:OutputStream out = new FileOutputStream(storePath+"\\"+uploadStuffFileName);InputStream in = new FileInputStream(uploadStuff);byte b[] = new byte[1024];int len = -1;while((len=in.read(b))!=-1){out.write(b, 0, len);}out.close();in.close();// 方法二:直接使用org.apache.commons.io.FileUtils的copyFile方法上传文件FileUtils.copyFile(uploadStuff, new File(storePath,uploadStuffFileName));return SUCCESS;}}// 多文件上传public class MyAction2 extends BaseAction implements Serializable {private File[] uploadStuff;private String[] uploadStuffFileName;private String[] uploadStuffContentType;// 此处省略了getter和setter的方法public String upload(){try {if(uploadStuff!=null&&uploadStuff.length>0){ServletContext sc = ServletActionContext.getServletContext();String storePath = sc.getRealPath("/files");for(int i=0;i<uploadStuff.length;i++)FileUtils.copyFile(uploadStuff[i], new File(storePath,uploadStuffFileName[i]));}return SUCCESS;} catch (Exception e) {e.printStackTrace();return ERROR;}}}2)下载文件:struts.xml:<action name="template_*" class="templateAction" method="{1}"><!-- 下载用的用result是stream类型 --><result name="download" type="stream"><param name="inputName">inputStream</param><!-- 设置文件的类型,application/octet-stream 表示二进制 --><param name="contentType">application/octet-stream</param><!-- 通知客户端,以下载的方式打开资源 --><param name="contentDisposition">attachment;filename="${#fileName}.doc"</param></result></action>Action:public class TemplateAction extends BaseAction{private File upload; // 上传的文件private InputStream inputStream; // 下载用的流,注意:名字要和struts.xml文件中inputName的值对应,即<param name="inputName">inputStream</param>// 下载public String download() throws Exception {// 获取模板对象的信息Template template = templateService.getById(model.getId());String path = template.getPath();// 准备默认的文件名String fileName = template.getName();fileName = URLEncoder.encode(fileName, "utf-8"); // 解决下载的文件名的乱码问题ActionContext.getContext().put("fileName", fileName);// 准备要下载的数据inputStream = new FileInputStream(path);return "download";}

0 0
原创粉丝点击