struts2文件下载

xiaoxiao2022-06-12  30

下面是jsp文件的代码:

<%@pagelanguage="java"import="java.io.*"pageEncoding="GBK"%> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html><head> <title>MyJSP'down.jsp'startingpage</title> <metahttp-equiv="pragma"content="no-cache"> <metahttp-equiv="cache-control"content="no-cache"> <metahttp-equiv="expires"content="0"> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="Thisismypage"> <!-- <linkrel="stylesheet"type="text/css"href="styles.css"> --></head><body><% //取得服务器"/download"目录的物理路径 Stringpath=request.getRealPath("/download"); //取得"/download/file"目录的file对象 Filefile=newFile(path); //取得file目录下所有文件 File[]files=file.listFiles(); for(inti=0;i<files.length;i++){ Stringfname=files[i].getName(); //对文件名进行url编码(UTF-8指明fname原来的编码,UTF-8一般由本地编码GBK代替) fname=java.net.URLEncoder.encode(fname,"UTF-8"); out.println("<ahref=download.action?name="+fname+">" +files[i].getName()+"</a><br>"); }%></body></html>

struts.xml相应的Action配置:

<actionname="download"class="com.hxz.action.DownloadAction"> <resultname="success"type="stream"> <paramname="contentType">application/rar</param> <paramname="inputName">targetFile</param> <paramname="contentDisposition">attachment;filename="${fileName}"</param> <paramname="bufferSize">4096</param> </result></action>

DownloadAction

packagecom.hxz.action;importjava.io.InputStream;importjava.io.UnsupportedEncodingException;importorg.apache.struts2.ServletActionContext;importcom.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") publicclassDownloadActionextendsActionSupport{ privateStringfileName; publicvoidsetFileName(){ //得到请求下载的文件名 Stringfname=ServletActionContext.getRequest().getParameter("name"); try{ /* *对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。*这里使用request.setCharacterEncoding解码无效.*只有解码了getTargetFile()方法才能在下载目录下正确找到请求的文件 **/ fname=newString(fname.getBytes("ISO-8859-1"),"UTF-8"); }catch(Exceptione){ e.printStackTrace();} this.fileName=fname; System.out.println(fileName); } /* *@getFileName*此方法对应的是struts.xml文件中的:*<paramname="contentDisposition">attachment;filename="${fileName}"</param>*这个属性设置的是下载工具下载文件时显示的文件名,*要想正确的显示中文文件名,我们需要对fileName再次编码*否则中文名文件将出现乱码,或无法下载的情况 **/ publicStringgetFileName()throwsUnsupportedEncodingException{ fileName=newString(fileName.getBytes(),"ISO-8859-1"); returnfileName; } publicInputStreamgetTargetFile()throwsException{ this.setFileName(); returnServletActionContext.getServletContext().getResourceAsStream(("/download/"+fileName)); } publicStringexecute()throwsException{ returnSUCCESS; }}
转载请注明原文地址: https://www.6miu.com/read-4934168.html

最新回复(0)