慕勒9281266
2016-11-18 17:46
//Action private List<File> upload; private List<String> uploadContentType; private List<String> uploadFileName; private String result; private String inputPath; private String filename; set/get方法省略 @Override public String execute() throws Exception { if(upload==null){ result = "请选择文件"; return INPUT; } String path = ServletActionContext.getServletContext().getRealPath("/images"); System.out.println(path); File file = new File(path); if(!file.exists()){ file.mkdirs(); } int i=0; //循环将批量上传的文件保存到本地 for (i = 0; i < upload.size(); i++) { FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i))); } System.out.println("共上传了:"+i+"个文件"); result="上传成功"; return SUCCESS; } /* * 下载action */ public InputStream getDownload() throws IOException{ String path = ServletActionContext.getServletContext().getRealPath("/images/"); String filepath = path+filename; System.out.println("路径为:"+filepath); File file = new File(filepath); //像页面输出流 return FileUtils.openInputStream(file); }
//配置文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 配置临时文件位置 --> <constant name="struts.multipart.saveDir" value="/tmp"/> <!-- 配置国际化信息 对应app是指配置文件的基础名称 里面key为异常信息,value为提示信息 --> <constant name="struts.custom.i18n.resources" value="app"></constant> <package name="uploadAndDownload" extends="struts-default"> <action name="uploadAndDownload3" class="com.imooc.action.BatchUploadAndDownloadAction"> <result>/03.jsp</result> <result name="input">/03.jsp</result> <!-- 配置拦截器 --> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/png</param> <param name="maximumSize">2M</param> </interceptor-ref> <!-- 配置默认拦截器 如果不配置则获取不到file--> <interceptor-ref name="defaultStack"></interceptor-ref> </action> <action name="download3" class="com.imooc.action.BatchUploadAndDownloadAction" method="getDownload"> <param name="inputPath">/images/img2-lg.jpg</param> <result type="stream"> <param name="contentType">application/octet-stream</param> <!-- 由getDownloadFile()获得inputStream --> <param name="inputName">download</param> <param name="contentDisposition">attachment;filename="${filename}"</param> <param name="bufferSize">8192</param> </result> </action> </package> </struts>
//页面 <a href="download3?filename=img2-lg.jpg">测试.jpg</a> ${error}
没有找到到底错在哪里,点下载就报错,找了好久没找到原因啊~~~
找到原因了 ,在编写action配置的时候,对应action指向了method,返回的InputSteam无法被转换成String,所以按照教程,修改action配置即可。
Java中的文件上传下载
77393 学习 · 337 问题
相似问题