在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

java中struts2实现文件上传下载功能

2016-7-29 15:34| 发布者: zhangjf| 查看: 724| 评论: 0

摘要: 先谈一谈struts2实现文件的上传和下载实例实现的原理: Struts 2是通过Commons FileUpload文件上传。 Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实 ...

先谈一谈struts2实现文件的上传和下载实例实现的原理

Struts 2是通过Commons FileUpload文件上传。

Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。

具体实现

一、创建index.jsp页面

  1. <body>
  2. <s:form action="upload" method="post" theme="simple" enctype="multipart/form-data">
  3. <table align="center" width="50%" border="1">
  4. <tr>
  5. <td>选择上传文件</td>
  6. <td id="more">
  7. <s:file name="file"></s:file>
  8. <input type="button" value="Add More.." onclick="addMore()">
  9. </td>
  10. </tr>
  11. <tr>
  12. <td><s:submit type="button" value="submit" onclick="return checkf()"/></td>
  13. <td><s:reset value="reset "></s:reset></td>
  14. </tr>
  15. </table>
  16. <table align="center" width="50%" border="1">
  17. <tr>
  18. <td>测试.txt</td>
  19. <td>
  20. <a href="<s:url value='download.action'><s:param name='fileName'>测试.txt</s:param> </s:url>">下载</a>
  21. </td>
  22. </tr>
  23. </table>
  24. </s:form>
  25. </body>
复制代码

创建result.jsp页面

  1. <body>
  2. <s:form>
  3. <div style="border:1px solid black">成功上传的文件:<br>
  4. <ul style="list-style-type:decimal">
  5. <s:iterator value="#request.fileName" id="file" status="status">
  6. <li><s:property/> </li>
  7. </s:iterator>
  8. </ul>
  9. </div>
  10. </s:form>
  11. </body>
复制代码

当然别忘了在每个页面上都添加上struts2 标签引用<%@taglib prefix="s" uri="/struts-tags" %>

二、创建updown.js文件,在index.jsp中引用

  1. function checkf(){
  2. var files = document.getElementsByName("file");
  3. if(files[0].value.length!=0){
  4. return true;
  5. }else{
  6. alert("请选择文件");
  7. return false;
  8. }
  9. }
  10. function addMore()
  11. {
  12. var td = document.getElementById("more");
  13. var br = document.createElement("br");
  14. var input = document.createElement("input");
  15. var button = document.createElement("input");
  16. input.type = "file";
  17. input.name = "file";
  18. button.type = "button";
  19. button.value = "Remove";
  20. button.onclick = function()
  21. {
  22. td.removeChild(br);
  23. td.removeChild(input);
  24. td.removeChild(button);
  25. }
  26. td.appendChild(br);
  27. td.appendChild(input);
  28. td.appendChild(button);
  29. }
复制代码

三、创建upDownloadAction.java

  1. package com.action;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.UnsupportedEncodingException;
  9. import java.util.List;
  10. import javax.servlet.http.HttpServletRequest;
  11. import com.opensymphony.xwork2.ActionSupport;
  12. import org.apache.struts2.ServletActionContext;
  13. public class UpDownloadAction extends ActionSupport {
  14. private static final long serialVersionUID = 1L;
  15. private List<File> file;// 对应jsp中file标签
  16. private List<String> fileFileName;//
  17. private List<String> fileContentType;//
  18. private String fileName;//获得jsp中pram参数
  19. @SuppressWarnings("deprecation")
  20. // 文件上传
  21. public String uploadFiile() throws Exception {
  22. String root = ServletActionContext.getServletContext().getRealPath(
  23. "/upload");// 上传路径
  24. System.out.println(root);
  25. InputStream inputStream;
  26. File destFile;
  27. OutputStream os;
  28. for (int i = 0; i < file.size(); i++) {
  29. inputStream = new FileInputStream(file.get(i));
  30. destFile = new File(root, this.getFileFileName().get(i));
  31. os = new FileOutputStream(destFile);
  32. byte[] buffer = new byte[400];
  33. int length = 0;
  34. while ((length = inputStream.read(buffer)) > 0) {
  35. os.write(buffer, 0, length);
  36. }
  37. inputStream.close();
  38. os.close();
  39. }
  40. HttpServletRequest request = ServletActionContext.getRequest();
  41. request.setAttribute("fileName", fileFileName);
  42. return SUCCESS;
  43. }
  44. // 文件下载
  45. public InputStream getDownloadFile() throws FileNotFoundException,
  46. UnsupportedEncodingException {
  47. System.out.println(getFileName());
  48. // 如果下载文件名为中文,进行字符编码转换
  49. ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="
  50. + java.net.URLEncoder.encode(fileName, "UTF-8"));
  51. InputStream inputStream = new FileInputStream("F:/" //使用绝对路径 ,从该路径下载“测试.txt"文件
  52. + this.getFileName());
  53. System.out.println(inputStream);
  54. return inputStream;
  55. }
  56. // 下载
  57. public String downloadFile() throws Exception {
  58. return SUCCESS;
  59. }
  60. public String getFileName() throws UnsupportedEncodingException {
  61. return fileName;
  62. }
  63. public void setFileName(String fileName)
  64. throws UnsupportedEncodingException {
  65. this.fileName = new String(fileName.getBytes("ISO8859-1"), "utf-8");
  66. }
  67. }
复制代码

注:属性的 get和set方法已省略。

四、最后是配置文件

1、web.xml配置

  1. <filter>
  2. <filter-name>struts2</filter-name>
  3. <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  4. </filter>
  5. <filter-mapping>
  6. <filter-name>struts2</filter-name>
  7. <url-pattern>/*</url-pattern>
  8. </filter-mapping>
复制代码

2、struts.xml配置

  1. <struts>
  2. <constant name="struts.i18n.encoding" value="utf-8"></constant>
  3. <constant name="struts.multipart.saveDir" value="f:"></constant>
  4. <package name="struts2" extends="struts-default">
  5. <action name="upload" class="com.action.UpDownloadAction" method="uploadFiile">
  6. <result name="success">/jsp/result.jsp</result>
  7. <interceptor-ref name="fileUpload">
  8. <!--maximumSize (可选) - 这个拦截器允许的上传到action中的文件最大长度(以byte为单位).
  9. 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB-->
  10. <param name="maximumSize">409600</param>
  11. <!--allowedTypes (可选) - 以逗号分割的contentType类型列表(例如text/html),
  12. 这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型.-->
  13. <param name="allowedTypes">
  14. text/plain
  15. </param>
  16. </interceptor-ref>
  17. <interceptor-ref name="defaultStack"></interceptor-ref>
  18. </action>
  19. <action name="download" class="com.action.UpDownloadAction" method="downloadFile" >
  20. <result name="success" type="stream">
  21. <!--指定文件下载类型 application/octet-stream默认值可以下载所有类型 -->
  22. <param name="contentType">
  23. application/txt;
  24. </param>
  25. <!-- 指定下载的文件名和显示方式 ,但注意中文名的乱码问题,解决办法是:进行编码处理-->
  26. <!--contentDisposition是文件下载的处理方式,包括内联(inline)和附件(attachment),
  27. 默认是inline, 使用附件时这样配置:attachment;filename="文件名" 。-->
  28. <param name="contentDisposition">
  29. attachment;filename="${fileName}"
  30. </param>
  31. <!--由getDownloadFile()方法获得inputStream-->
  32. <param name="inputName">downloadFile</param>
  33. <!-- 指定下载文件的缓存大小-->
  34. <param name="bufferSize">2048</param>
  35. </result>
  36. </action>
  37. </package>
  38. </struts>
复制代码

一个简单的Struts2多文件上传单文件下载就实现了。

以上就是本文的全部内容,希望对大家的学习有所帮助。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:41

Copyright 2015-2025 djqfx

返回顶部