struts2 文件的上传和下载


Struts2 中的文件上传和下载 @author 晓峰 @date 2012 年 2 月 27 日 9:37:30 第一步、准备好相应的包 commons-fileupload-1.2.2.jar 和 commons-io-2.0.1.jar,其余包如下 第二步、新建 web project 工程 TestUploadAndDownload,其总体架构如下图 第三步、配置 web.xml 和 struts.xml web.xml struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilt er struts2 /* struts-cleanup org.apache.struts2.dispatcher.ActionContextCleanUp struts-cleanup /* upload.jsp struts2.xml /download.jsp /upload.jsp 2097152 application/msword,application/vnd.openxmlformats-officedocumen t.wordprocessingml.document,application/vnd.ms-excel attachment;filename="${fileName}" ${flen} downloadFile /upload.jsp 第四步、编写文件上传页面以及上传的 action 类 upload.jsp <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> 文件上传和下载测试页面
文件上传
file.js var flag=1; function addFile() { var txt=document.getElementById("txt1").innerHTML; var tb=document.getElementById("tb1"); var tr1=document.getElementById("tr1"); var tr=document.createElement("tr"); flag++; txt=txt+flag; var txt2=document.createTextNode(txt); var file2=document.createElement("input"); file2.type="file"; file2.name="file" var button=document.createElement("input"); button.type="button"; button.value="删除"; button.onclick=function(){ tr.removeChild(td1); tr.removeChild(td2); tb.removeChild(tr); } var td1=document.createElement("td"); td1.appendChild(txt2); var td2=document.createElement("td"); td2.appendChild(file2); td2.appendChild(button); tr.appendChild(td1); tr.appendChild(td2); tr1.insertBefore(tr,null); } FileUpload.java package com.xiaofeng.service; import com.opensymphony.xwork2.ActionSupport; import java.util.*; import java.util.logging.Logger; import java.io.*; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; @SuppressWarnings("deprecation") public class FileUpload extends ActionSupport{ /** *@author xiaofeng *@serial v1.0 */ private static final Logger log=Logger.getLogger(FileUpload.class.getName()); //设置字节数组的大小 private static final int BUFFSIZE=10*1024*1024; //获取的路径是 tomcat 安装目录下的 webapp 下工程的 upload 目录。 //ServletActionContext.getRequest().getRealPath("upload") //文件上传的目录 private static final String root="c:/upload/"; private static final long serialVersionUID = 1L; //所接收的文件 private List file; //文件类型 private List fileContentType; //文件名字 private List fileFileName; public List getFile() { return file; } public void setFile(List file) { this.file = file; } public List getFileContentType() { return fileContentType; } public void setFileContentType(List fileContentType) { this.fileContentType = fileContentType; } public List getFileFileName() { return fileFileName; } public void setFileFileName(List fileFileName) { this.fileFileName = fileFileName; } @Override public String execute() throws Exception { int length=0; List fileName=new ArrayList(); List rootPath=new ArrayList(); String name=null; for(int i=0;i0) { os.write(br, 0, length); } is.close(); os.close(); } HttpServletRequest request=ServletActionContext.getRequest(); request.setAttribute("file_list", rootPath); request.setAttribute("file_name_list", fileName); return SUCCESS; } } 第五步、编写文件下载页面 download.jsp 以及下载 action 类. download.jsp <%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <%@page import="java.io.*" %> <%@ taglib prefix="s" uri="/struts-tags" %> 上传成功页面 上传成功!请点击下面链接进行下载
<% //取得服务器"c:/upload/file"目录的物理路径 String path ="c:/upload"; //取得"c:/upload/file"目录的file对象 File file = new File(path); //取得file目录下所有文件 File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { String fname = files[i].getName(); //对文件名进行url编码(UTF-8指明fname原来的编码,UTF-8一般由本地编码GBK代 替) fname = java.net.URLEncoder.encode(fname, "UTF-8"); out.println("" + files[i].getName() + "
"); } %> FileDownLoad.java package com.xiaofeng.service; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class FileDownLoad extends ActionSupport{ /** * @author :xiaofeng * @date :2012 年 2 月 23 日 17:18:03 * @serial :v1.0 */ private static final long serialVersionUID = 9048071785232069492L; private String fileName; private String flen; public String getFlen() { return flen; } public void setFlen() { this.flen = ServletActionContext.getRequest().getParameter("len"); } public void setFileName() { //得到请求下载的文件名 String fname = ServletActionContext.getRequest().getParameter("name"); try { /* * 对 fname 参数进行 UTF-8 解码,注意:实际进行 UTF-8 解码时会使用本地 编码,本机为 GBK。 * 这里使用 request.setCharacterEncoding 解码无效. * 只有解码了 getDownloadFile()方法才能在下载目录下正确找到请求的文 件 * */ fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } this.fileName = fname; } /* * @getFileName * 此方法对应的是 struts.xml 文件中的: * attachment;filename="${fileName}" * 这个属性设置的是下载工具下载文件时显示的文件名, * 要想正确的显示中文文件名,我们需要对 fileName 再次编码 * 否则中文名文件将出现乱码,或无法下载的情况 * */ public String getFileName() throws UnsupportedEncodingException { fileName=new String(fileName.getBytes(),"ISO-8859-1"); return fileName; } /* * @getDownloadFile * 此方法对应的是 struts.xml 文件中的: * downloadFile * 返回下载文件的流,可以参看 struts2 的源码 * */ public InputStream getDownloadFile() throws FileNotFoundException { this.setFileName(); this.setFlen(); return new FileInputStream("c:/upload/" + fileName); } @Override public String execute() throws Exception { return SUCCESS; } } 第六步、演示效果。 图一 图二 图三 附录:ContentType 表 response.setContentType() ;参数 response.setContentType() ; * = application/octet-stream .001 = application/x-001 .301 = application/x-301 .323 = text/h323 .906 = application/x-906 .907 = drawing/907 .a11 = application/x-a11 .acp = audio/x-mei-aac .ai = application/postscript .aif = audio/aiff .aifc = audio/aiff .aiff = audio/aiff .anv = application/x-anv .asa = text/asa .asf = video/x-ms-asf .asp = text/asp .asx = video/x-ms-asf .au = audio/basic .avi = video/avi .awf = application/vnd.adobe.workflow .biz = text/xml .bmp = application/x-bmp .bot = application/x-bot .c4t = application/x-c4t .c90 = application/x-c90 .cal = application/x-cals .cat = application/vnd.ms-pki.seccat .cdf = application/x-netcdf .cdr = application/x-cdr .cel = application/x-cel .cer = application/x-x509-ca-cert .cg4 = application/x-g4 .cgm = application/x-cgm .cit = application/x-cit .class = java/* .cml = text/xml :客户端浏览器按 XML 格式进行解析文档 .cmp = application/x-cmp .cmx = application/x-cmx .cot = application/x-cot .crl = application/pkix-crl .crt = application/x-x509-ca-cert .csi = application/x-csi .css = text/css :客户端浏览器按 CSS 格式进行解析文档 .cut = application/x-cut .dbf = application/x-dbf .dbm = application/x-dbm .dbx = application/x-dbx .dcd = text/xml :客户端浏览器按 XML 格式进行解析文档 .dcx = application/x-dcx .der = application/x-x509-ca-cert .dgn = application/x-dgn .dib = application/x-dib .dll = application/x-msdownload .doc = application/msword .dot = application/msword .drw = application/x-drw .dtd = text/xml :客户端浏览器按 XML 格式进行解析文档 .dwf = Model/vnd.dwf .dwf = application/x-dwf .dwg = application/x-dwg .dxb = application/x-dxb .dxf = application/x-dxf .edn = application/vnd.adobe.edn .emf = application/x-emf .eml = message/rfc822 .ent = text/xml :客户端浏览器按 XML 格式进行解析文档 .epi = application/x-epi .eps = application/x-ps .eps = application/postscript .etd = application/x-ebx .exe = application/x-msdownload .fax = image/fax .fdf = application/vnd.fdf .fif = application/fractals .fo = text/xml :客户端浏览器按 XML 格式进行解析文档 .frm = application/x-frm .g4 = application/x-g4 .gbr = application/x-gbr .gcd = application/x-gcd .gif = image/gif .gl2 = application/x-gl2 .gp4 = application/x-gp4 .hgl = application/x-hgl .hmr = application/x-hmr .hpg = application/x-hpgl .hpl = application/x-hpl .hqx = application/mac-binhex40 .hrf = application/x-hrf .hta = application/hta .htc = text/x-component .htm = text/html :客户端浏览器按超文本格式进行解析文档 .html = text/html :客户端浏览器按超文本格式进行解析文档 .htt = text/webviewhtml .htx = text/html :客户端浏览器按超文本格式进行解析文档 .icb = application/x-icb .ico = image/x-icon .ico = application/x-ico .iff = application/x-iff .ig4 = application/x-g4 .igs = application/x-igs .iii = application/x-iphone .img = application/x-img .ins = application/x-internet-signup .isp = application/x-internet-signup .IVF = video/x-ivf .java = java/* .jfif = image/jpeg .jpe = image/jpeg .jpe = application/x-jpe .jpeg = image/jpeg .jpg = image/jpeg .jpg = application/x-jpg .js = application/x-javascript .jsp = text/html :客户端浏览器按超文本格式进行解析文档 .la1 = audio/x-liquid-file .lar = application/x-laplayer-reg .latex = application/x-latex .lavs = audio/x-liquid-secure .lbm = application/x-lbm .lmsff = audio/x-la-lms .ls = application/x-javascript .ltr = application/x-ltr .m1v = video/x-mpeg .m2v = video/x-mpeg .m3u = audio/mpegurl .m4e = video/mpeg4 .mac = application/x-mac .man = application/x-troff-man .math = text/xml .mdb = application/msaccess .mdb = application/x-mdb .mfp = application/x-shockwave-flash .mht = message/rfc822 .mhtml = message/rfc822 .mi = application/x-mi .mid = audio/mid .midi = audio/mid .mil = application/x-mil .mml = text/xml .mnd = audio/x-musicnet-download .mns = audio/x-musicnet-stream .mocha = application/x-javascript .movie = video/x-sgi-movie .mp1 = audio/mp1 .mp2 = audio/mp2 .mp2v = video/mpeg .mp3 = audio/mp3 .mp4 = video/mpeg4 .mpa = video/x-mpg .mpd = application/vnd.ms-project .mpe = video/x-mpeg .mpeg = video/mpg .mpg = video/mpg .mpga = audio/rn-mpeg .mpp = application/vnd.ms-project .mps = video/x-mpeg .mpt = application/vnd.ms-project .mpv = video/mpg .mpv2 = video/mpeg .mpw = application/vnd.ms-project .mpx = application/vnd.ms-project .mtx = text/xml .mxp = application/x-mmxp .net = image/pnetvue .nrf = application/x-nrf .nws = message/rfc822 .odc = text/x-ms-odc .out = application/x-out .p10 = application/pkcs10 .p12 = application/x-pkcs12 .p7b = application/x-pkcs7-certificates .p7c = application/pkcs7-mime .p7m = application/pkcs7-mime .p7r = application/x-pkcs7-certreqresp .p7s = application/pkcs7-signature .pc5 = application/x-pc5 .pci = application/x-pci .pcl = application/x-pcl .pcx = application/x-pcx .pdf = application/pdf :客户端浏览器按 PDF 格式进行解析文档 .pdf = application/pdf .pdx = application/vnd.adobe.pdx .pfx = application/x-pkcs12 .pgl = application/x-pgl .pic = application/x-pic .pko = application/vnd.ms-pki.pko .pl = application/x-perl .plg = text/html .pls = audio/scpls .plt = application/x-plt .png = image/png .png = application/x-png .pot = application/vnd.ms-powerpoint .ppa = application/vnd.ms-powerpoint .ppm = application/x-ppm .pps = application/vnd.ms-powerpoint .ppt = application/vnd.ms-powerpoint .ppt = application/x-ppt .pr = application/x-pr .prf = application/pics-rules .prn = application/x-prn .prt = application/x-prt .ps = application/x-ps .ps = application/postscript .ptn = application/x-ptn .pwz = application/vnd.ms-powerpoint .r3t = text/vnd.rn-realtext3d .ra = audio/vnd.rn-realaudio .ram = audio/x-pn-realaudio .ras = application/x-ras .rat = application/rat-file .rdf = text/xml .rec = application/vnd.rn-recording .red = application/x-red .rgb = application/x-rgb .rjs = application/vnd.rn-realsystem-rjs .rjt = application/vnd.rn-realsystem-rjt .rlc = application/x-rlc .rle = application/x-rle .rm = application/vnd.rn-realmedia .rmf = application/vnd.adobe.rmf .rmi = audio/mid .rmj = application/vnd.rn-realsystem-rmj .rmm = audio/x-pn-realaudio .rmp = application/vnd.rn-rn_music_package .rms = application/vnd.rn-realmedia-secure .rmvb = application/vnd.rn-realmedia-vbr .rmx = application/vnd.rn-realsystem-rmx .rnx = application/vnd.rn-realplayer .rp = image/vnd.rn-realpix .rpm = audio/x-pn-realaudio-plugin .rsml = application/vnd.rn-rsml .rt = text/vnd.rn-realtext .rtf = application/msword .rtf = application/x-rtf .rv = video/vnd.rn-realvideo .sam = application/x-sam .sat = application/x-sat .sdp = application/sdp .sdw = application/x-sdw .sit = application/x-stuffit .slb = application/x-slb .sld = application/x-sld .slk = drawing/x-slk .smi = application/smil .smil = application/smil .smk = application/x-smk .snd = audio/basic .sol = text/plain .sor = text/plain .spc = application/x-pkcs7-certificates .spl = application/futuresplash .spp = text/xml .ssm = application/streamingmedia .sst = application/vnd.ms-pki.certstore .stl = application/vnd.ms-pki.stl .stm = text/html .sty = application/x-sty .svg = text/xml .swf = application/x-shockwave-flash :客户端浏览器按 Flash 格式进行解析文档 .tdf = application/x-tdf .tg4 = application/x-tg4 .tga = application/x-tga .tif = image/tiff .tif = application/x-tif .tiff = image/tiff .tld = text/xml .top = drawing/x-top .torrent = application/x-bittorrent .tsd = text/xml .txt = text/plain :客户端浏览器按 纯文本 格式进行解析文档 .uin = application/x-icq .uls = text/iuls .vcf = text/x-vcard .vda = application/x-vda .vdx = application/vnd.visio .vml = text/xml .vpg = application/x-vpeg005 .vsd = application/vnd.visio .vsd = application/x-vsd .vss = application/vnd.visio .vst = application/vnd.visio .vst = application/x-vst .vsw = application/vnd.visio .vsx = application/vnd.visio .vtx = application/vnd.visio .vxml = text/xml .wav = audio/wav .wax = audio/x-ms-wax .wb1 = application/x-wb1 .wb2 = application/x-wb2 .wb3 = application/x-wb3 .wbmp = image/vnd.wap.wbmp .wiz = application/msword .wk3 = application/x-wk3 .wk4 = application/x-wk4 .wkq = application/x-wkq .wks = application/x-wks .wm = video/x-ms-wm .wma = audio/x-ms-wma .wmd = application/x-ms-wmd .wmf = application/x-wmf .wml = text/vnd.wap.wml .wmv = video/x-ms-wmv .wmx = video/x-ms-wmx .wmz = application/x-ms-wmz .wp6 = application/x-wp6 .wpd = application/x-wpd .wpg = application/x-wpg .wpl = application/vnd.ms-wpl .wq1 = application/x-wq1 .wr1 = application/x-wr1 .wri = application/x-wri .wrk = application/x-wrk .ws = application/x-ws .ws2 = application/x-ws .wsc = text/scriptlet .wsdl = text/xml .wvx = video/x-ms-wvx .xdp = application/vnd.adobe.xdp .xdr = text/xml .xfd = application/vnd.adobe.xfd .xfdf = application/vnd.adobe.xfdf .xhtml = text/html .xls = application/vnd.ms-excel .xls = application/x-xls .xlw = application/x-xlw .xml = text/xml .xpl = audio/scpls .xq = text/xml .xql = text/xml .xquery = text/xml .xsd = text/xml .xsl = text/xml .xslt = text/xml .xwd = application/x-xwd .x_b = application/x-x_b .x_t = application/x-x_t
还剩18页未读

继续阅读

下载pdf到电脑,查找使用更方便

pdf的实际排版效果,会与网站的显示效果略有不同!!

需要 5 金币 [ 分享pdf获得金币 ] 6 人已下载

下载pdf

pdf贡献者

xiaofeng

贡献于2012-03-09

下载需要 5 金币 [金币充值 ]
亲,您也可以通过 分享原创pdf 来获得金币奖励!
下载pdf