ITPub博客

首页 > 应用开发 > Java > Struts2 文件上传下载 含下载时中文乱码

Struts2 文件上传下载 含下载时中文乱码

Java 作者:dawn009 时间:2014-06-04 15:39:32 0 删除 编辑

------------->>转载于;http://blog.csdn.net/zjw10wei321/article/details/9031417
对于struts2一直都是看过,很少去动手写里面的功能,今天花了一点时间算整理整理。

整体的项目大致如下:


1:文件上传

uploadAction.java


[java] view plaincopy
  1. package action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import org.apache.commons.io.FileUtils;  
  9. import org.apache.struts2.ServletActionContext;  
  10.   
  11. import com.opensymphony.xwork2.ActionSupport;  
  12.   
  13. public class UploadAction extends ActionSupport {  
  14.   
  15.     private static final long serialVersionUID = -8920466592471253212L;  
  16.   
  17.     private String title;  
  18.     private File file; // 上传的文件  
  19.     private String fileFileName; // 文件名称  
  20.     private String fileContentType; // 文件类型  
  21.     private String savePath;  
  22.     private String contents = "";  
  23.   
  24.     public String execute() throws Exception {  
  25.         // String url = getSavePath() + File.separator + getFileFileName();  
  26.         String url = getSavePath();  
  27.         System.out.println("url==" + url + ",,," + getFileContentType());  
  28.         FileOutputStream fos = null;  
  29.         FileInputStream fis = null;  
  30.         try {  
  31.             // fos = new FileOutputStream(url);  
  32.             File uploadFile = new File(url, this.getFileFileName());  
  33.             fos = new FileOutputStream(uploadFile);  
  34.   
  35.             fis = new FileInputStream(getFile());  
  36.             byte[] buffer = new byte[1024 * 1024];  
  37.             int len = 0;  
  38.             while ((len = fis.read(buffer)) > 0) {  
  39.                 fos.write(buffer, 0, len);  
  40.                 setContents(getContents() + new String(buffer));  
  41.             }  
  42.             fos.flush();  
  43.         } catch (Exception e) {  
  44.             e.printStackTrace();  
  45.             return INPUT;  
  46.         } finally {  
  47.             close(fos, fis);  
  48.         }  
  49.         return SUCCESS;  
  50.     }  
  51.   
  52.     public File getFile() {  
  53.         return file;  
  54.     }  
  55.   
  56.     public void setFile(File file) {  
  57.         this.file = file;  
  58.     }  
  59.   
  60.     public String getFileFileName() {  
  61.         return fileFileName;  
  62.     }  
  63.   
  64.     public void setFileFileName(String fileFileName) {  
  65.         this.fileFileName = fileFileName;  
  66.     }  
  67.   
  68.     public String getFileContentType() {  
  69.         return fileContentType;  
  70.     }  
  71.   
  72.     public void setFileContentType(String fileContentType) {  
  73.         this.fileContentType = fileContentType;  
  74.     }  
  75.   
  76.     public String getTitle() {  
  77.         return title;  
  78.     }  
  79.   
  80.     public void setTitle(String title) {  
  81.         this.title = title;  
  82.     }  
  83.   
  84.     public String getSavePath() {  
  85.         String result = ServletActionContext.getServletContext().getRealPath(  
  86.                 savePath);  
  87.         return result;  
  88.     }  
  89.   
  90.     public void setSavePath(String savePath) {  
  91.         this.savePath = savePath;  
  92.     }  
  93.   
  94.     public String getContents() {  
  95.         return contents;  
  96.     }  
  97.   
  98.     public void setContents(String contents) {  
  99.         this.contents = contents;  
  100.     }  
  101.   
  102.     private void close(FileOutputStream fos, FileInputStream fis) {  
  103.         if (fis != null) {  
  104.             try {  
  105.                 fis.close();  
  106.             } catch (IOException e) {  
  107.                 System.out.println("FileInputStream关闭失败");  
  108.                 e.printStackTrace();  
  109.             }  
  110.         }  
  111.         if (fos != null) {  
  112.             try {  
  113.                 fos.close();  
  114.             } catch (IOException e) {  
  115.                 System.out.println("FileOutputStream关闭失败");  
  116.                 e.printStackTrace();  
  117.             }  
  118.         }  
  119.     }  
  120. }  



上传页面upload.jsp:

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. >  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.      <title>上传文件title>  
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.   head>  
  20.     
  21.   <body>  
  22.     <s:form action="uploads" method="post" enctype="multipart/form-data">  
  23.     <s:textfield id="title" name="title" label="文件标题"/>  
  24.     <s:file name="file" label="上传文件"/>  
  25.     <s:submit value="提交"/>  
  26.     s:form>  
  27.   
  28.   body>  
  29. html>  

上传成功uploadSuccess.jsp:


[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. >  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>My JSP 'index.jsp' starting pagetitle>  
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.   head>  
  20.     
  21.   <body>  
  22.     上传文件:<s:property value="title" /><br/>  
  23.     文件内容:  
  24.     <s:if test="%{fileContentType.indexOf('image')>=0}">  
  25.         <img src="<s:property value="'upload/'+fileFileName"/>"/>  
  26.     s:if>  
  27.     <s:else>  
  28.         <s:property value="contents"/>  
  29.     s:else>  
  30.   body>  
  31. html>  

主要的struts.xml:



[html] view plaincopy
  1. xml version="1.0" encoding="UTF-8" ?>  
  2. >  
  3. <struts>  
  4.     <constant name="struts.devMode" value="true" />  
  5.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  6.       
  7.     <package name="myDemo" extends="struts-default" namespace="/">  
  8.       
  9.         <action name="uploads" class="action.UploadAction" >  
  10.             <param name="savePath">/uploadparam>  
  11.             <result name="input">/upload.jspresult>  
  12.             <result name="success">/uploadSuccess.jspresult>  
  13.         action>  
  14.         <action name="downloads" class="action.DownloadAction">  
  15.             <param name="inputPath">uploadparam>  
  16.             <result name="input">/downloadSuccess.jspresult>  
  17.             <result name="success" type="stream">  
  18.                 <param name="contentType">application/octet-stream;charset=ISO8859-1 param>  
  19.                 <param name="inputName">downloadFileparam>  
  20.                 <param name="contentDisposition">attachment;filename="${downloadFileName}"param>  
  21.                 <param name="bufferSize">4096param>  
  22.             result>  
  23.         action>  
  24.           
  25.         <action name="download" class="action.DownloadAction" method="download">  
  26.             <param name="inputPath">uploadparam>  
  27.             <result name="success" >/download.jsp  
  28.             result>  
  29.         action>  
  30.   
  31.         <!-- <action name="*">  
  32.             <result>/{1}.jspresult>  
  33.         action> -->  
  34.     package>  
  35. struts>      


对于上传主要在action哩,主要有3个属性:***、***FileName、***ContentTyp。我的例子**为file。


成功后,页面若是图片形式,我把它显示出来,如果不是就显示里面的内容。


2:文件下载

文件下载主要配置在struts.xml里。

一般使用result=“stream” 在struts中进行文件下载

有4个参数:contentType(主要)、contentDisposition(主要)、inputName、bufferSize,相对于这2个主要些。

详细的可以参考这个页面:强烈碰击

常常也会在下载的时候碰到一个异常:Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the tag specified for this action.

主要为2中情况:

第一:文件路径不对,没有取到文件,只需要在return之前,把流放在system.out.println()中输出一下,是null的话,就是路径不对。

第二:action中需要配置""后面属性的那个get方法。


下载action:downloadAction.java


[java] view plaincopy
  1. package action;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.UnsupportedEncodingException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import org.apache.struts2.ServletActionContext;  
  10.   
  11. import com.opensymphony.xwork2.ActionSupport;  
  12.   
  13. public class DownloadAction extends ActionSupport {  
  14.   
  15.     private static final long serialVersionUID = -5772950074616179246L;  
  16.     // the download file  
  17.     private String fileName;  
  18.     // the download folder  
  19.     private String inputPath;  
  20.   
  21.     // all files of the download folder  
  22.     private List fileNames;  
  23.   
  24.     public String getFileName() {  
  25.         return fileName;  
  26.     }  
  27.   
  28.     public void setFileName(String fileName) {  
  29.         //System.out.println("----"+fileName);  
  30.         try {  
  31.             fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");  
  32.         } catch (UnsupportedEncodingException e) {  
  33.             e.printStackTrace();  
  34.         }  
  35.         //System.out.println("----"+fileName);  
  36.         this.fileName = fileName;  
  37.     }  
  38.   
  39.     public String getInputPath() {  
  40.         return inputPath;  
  41.     }  
  42.   
  43.     public void setInputPath(String inputPath) {  
  44.         this.inputPath = inputPath;  
  45.     }  
  46.   
  47.     public InputStream getDownloadFile() {  
  48.         String urll = File.separator + inputPath + File.separator + fileName;  
  49.         InputStream is = ServletActionContext.getServletContext()  
  50.                 .getResourceAsStream(urll);  
  51.         //System.out.println(urll+"-----"+fileName+"---"+is);  
  52.         return is;  
  53.     }  
  54.   
  55.     public String getDownloadFileName() {  
  56.         String downFileName = fileName;  
  57.         //System.out.println("----"+downFileName);  
  58.         try {  
  59.             downFileName = new String(downFileName.getBytes(), "ISO8859-1");  
  60.         } catch (UnsupportedEncodingException e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.         //System.out.println("----"+downFileName);  
  64.         return downFileName;  
  65.   
  66.     }  
  67.   
  68.     public String download() throws Exception {  
  69.         String downloadDir = ServletActionContext.getServletContext()  
  70.                 .getRealPath(File.separator + inputPath);  
  71.         File rootFile = new File(downloadDir);  
  72.         File[] files = rootFile.listFiles();  
  73.         fileNames = new ArrayList();  
  74.         for (File f : files) {  
  75.             if (!f.isDirectory()) {  
  76.                 String name = f.getName();  
  77.                 //System.out.println(name);  
  78.                 fileNames.add(name);  
  79.             }  
  80.         }  
  81.         return SUCCESS;  
  82.     }  
  83.   
  84.     public List getFileNames() {  
  85.         return fileNames;  
  86.     }  
  87.   
  88.     public void setFileNames(List fileNames) {  
  89.         this.fileNames = fileNames;  
  90.     }  
  91.   
  92. }  

下载页面download.jsp:



[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags"%>  
  3. >  
  4. <html>  
  5. <head>  
  6. <title>My JSP 'index.jsp' starting pagetitle>  
  7. <meta http-equiv="pragma" content="no-cache">  
  8. <meta http-equiv="cache-control" content="no-cache">  
  9. <meta http-equiv="expires" content="0">  
  10. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  11. <meta http-equiv="description" content="This is my page">  
  12. head>  
  13.   
  14. <body>  
  15.     <font color="blue">--------------------------font>  
  16.     <br>  
  17.   
  18.     <s:iterator value="fileNames" var="file">  
  19.         <s:set value="file" id="files" name="files" scope="Request"/>  
  20.         <%  
  21.         String fname = (String)request.getAttribute("files");  
  22.         fname = java.net.URLEncoder.encode(fname, "UTF-8");  
  23.         %>  
  24.         <a href="downloads.action?fileName=<%=fname %>">   
  25.             <s:property value="file" />下载  
  26.         a>  
  27.         <br />  
  28.     s:iterator>  
  29. body>  
  30. html>  

3个乱码的地方:


a:前台中文,后台获取:


[java] view plaincopy
  1. public void setFileName(String fileName) {  
  2.         //System.out.println("----"+fileName);  
  3.         try {  
  4.             fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");  
  5.         } catch (UnsupportedEncodingException e) {  
  6.             e.printStackTrace();  
  7.         }  
  8.         //System.out.println("----"+fileName);  
  9.         this.fileName = fileName;  
  10.     }  
在未URLEncoder之前:



b:下载时显示中文名字:


[java] view plaincopy
  1. public String getDownloadFileName() {  
  2.         String downFileName = fileName;  
  3.         //System.out.println("----"+downFileName);  
  4.         try {  
  5.             downFileName = new String(downFileName.getBytes(), "ISO8859-1");  
  6.         } catch (UnsupportedEncodingException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.         //System.out.println("----"+downFileName);  
  10.         return downFileName;  
  11.   
  12.     }  

[html] view plaincopy
  1. <action name="downloads" class="action.DownloadAction">  
  2.             <param name="inputPath">uploadparam>  
  3.             <result name="input">/downloadSuccess.jspresult>  
  4.             <result name="success" type="stream">  
  5.                 <param name="contentType">application/octet-stream;charset=ISO8859-1 param>  
  6.                 <param name="inputName">downloadFileparam>  
  7.                 <param name="contentDisposition">attachment;filename="${downloadFileName}"param>  
  8.                 <param name="bufferSize">4096param>  
  9.             result>  
  10.         action>  




主要为action配置时配置contentDisposition参数,attachment;filename="${downloadFileName}",

取的就为getDownloadFileName()的值。


c:链接中的中文编码


[html] view plaincopy
  1. <s:iterator value="fileNames" var="file">  
  2.         <s:set value="file" id="files" name="files" scope="Request"/>  
  3.         <%  
  4.         String fname = (String)request.getAttribute("files");  
  5.         fname = java.net.URLEncoder.encode(fname, "UTF-8");  
  6.         %>  
  7.         <a href="downloads.action?fileName=<%=fname %>">   
  8.             <s:property value="file" />下载  
  9.         a>  
  10.         <br />  
  11.     s:iterator> 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29119536/viewspace-1175513/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-08-15

  • 博文量
    595
  • 访问量
    4989245