Struts2实现文件下载功能代码分享(文件名中文转码)
struts2文件下载功能实现代码如下所示:
Action文件
publicclassDownLoadActionextendsActionSupport{ /** * */ privatestaticfinallongserialVersionUID=5879762231742395104L; privateStringfileName;//用户请求的文件名 privateStringinputPath;//下载资源的路径(在struts配置文件中设置) publicvoidsetInputPath(StringinputPath){ this.inputPath=inputPath; } publicStringgetInputPath(){ returninputPath; } publicvoidsetFileName(StringfileName){ this.fileName=fileName; } publicStringgetFileName(){ returnfileName; } publicStringdownloadFile()throwsException{ ServletContextcontext=ServletActionContext.getServletContext(); StringdownloadDir=context.getRealPath("/upload"); StringdownloadFile=context.getRealPath(inputPath); //防止用户请求不安全的资源 if(!downloadFile.startsWith(downloadDir)){ returnnull; } return"download_success"; } /* *获取输入流资源 */ publicInputStreamgetInputStream()throwsException{ Stringpath=inputPath+File.separatorChar+newString(fileName.getBytes("ISO-8859-1"),"UTF-8"); returnServletActionContext.getServletContext().getResourceAsStream(path); } /* *获取下载时文件默认的文件名 */ publicStringgetDownloadFileName(){ StringdownloadFileName=fileName; try{ downloadFileName=URLEncoder.encode(downloadFileName,"ISO-8859-1"); }catch(UnsupportedEncodingExceptione){ e.getMessage(); e.printStackTrace(); } returndownloadFileName; } }
jsp文件:
<li> <ahref="<%=path%>/download_DownLoadAction_downloadFile.action?fileName=dwr.jar">dwr.jar文件下在</a> </li> <li> <ahref="<%=path%>/download_DownLoadAction_downloadFile.action?fileName=Struts2教程.pdf">Struts2教程.pdf文件下在</a> </li>
struts.xml:
<actionname="download_*_*"class="com.wang.action.{1}"method="{2}"> <paramname="inputPath">/upload</param> <!--resulttype设置为stream--> <resultname="download_success"type="stream"> <!--MIME类型--> <paramname="contentType">application/octet-stream</param> <!--inputName的值与action获取输入流资源的方法名相对应(action中定义getInputStream方法,并且返回类型为InputStream)--> <paramname="inputName">inputStream</param> <!--设置带附件的文件动态获取文件名(action中定义getDownloadFileName方法)--> <paramname="contentDisposition">attachment;filename="${downloadFileName}"</param> <!--设置缓冲大小--> <paramname="bufferSize">2048</param> </result> </action>
以上所述是小编给大家介绍的Struts2实现文件下载功能代码分享(文件名中文转码)的相关内容,希望对大家有所帮助!