java实现文件上传下载的三种方法

JSP+Servlet

一、文件上传下载原理

在TCP/IP中,最早出现的文件上传机制是FTP。它是将文件由客户端发送到服务器的标准机制。但是在jsp编程中不能使用FTP方法来上传文件,这是由jsp的运行机制所决定的。

通过为表单元素设置Method=“post” enctype="multipart/form-data"属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。

二、enctype属性的选择值范围

1、application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成url编码方式。

2、multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定的文件内容也封装到请求参数里。

3、text/plain:这种方式主要适用于直接通过表单发送邮件的方式。

代码内容

1.将文件读取到服务器指定目录下

2.获取文件内容的起止位置,和文件名称

3.将文件保存到项目的指定目录下

[html]  view plain  copy
  1. <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         //从request中获取输入流信息  
  4.         InputStream fileSource = request.getInputStream();  
  5.         //创建存储在服务器的路径信息  
  6.         String tempFileName = "H:/tempFile";  
  7.         //指向临时文件  
  8.         File tempFile = new File(tempFileName);  
  9.         //outPutStream输出流指向临时文件  
  10.         FileOutputStream outputStream = new FileOutputStream(tempFile);   
  11.         //每次读取文件字节  
  12.         byte b[] = new byte[1024];  
  13.         int n;  
  14.         while((n=fileSource.read(b))!=-1){  
  15.             outputStream.write(b,0,n);  
  16.         }  
  17.           
  18.         //关闭输出输入流  
  19.         fileSource.close();  
  20.         outputStream.close();  
  21.           
  22.         //获取上传文件的名称  
  23.         RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");  
  24.         randomFile.readLine();  //获取第一行数据(对我们来说没有意义)  
  25.         String str = randomFile.readLine();  //获取第二行数据,内容为:Content-Disposition: form-data; name="myfile"filename="C:\Users\lihf\Desktop\hello.txt"  
  26.         int beginIndex = str.lastIndexOf("\\")+1;  
  27.         int endIndex = str.lastIndexOf("\"");  
  28.         String fileName = str.substring(beginIndex, endIndex);  
  29.           
  30.         //重新定位文件指针到头文件  
  31.         randomFile.seek(0);  
  32.         long startPosition=0;  
  33.         int i=1;  
  34.         //获取文件内容开始位置  
  35.         while((n=randomFile.readByte())!=-1&&i<=4){  
  36.             if(n=='\n'){  
  37.                 startPosition = randomFile.getFilePointer();  
  38.                 i++;  
  39.             }  
  40.         }  
  41.         startPosition = randomFile.getFilePointer() -1;  
  42.         //获取文件结束位置  
  43.         randomFile.seek(randomFile.length());  //文件指针定位到文件末尾  
  44.         long endPosition = randomFile.getFilePointer();  
  45.         int j=1;  
  46.         while(endPosition>=0&&j<=2){  
  47.             endPosition--;  
  48.             randomFile.seek(endPosition);  
  49.             if(randomFile.readByte()=='\n'){  
  50.                 j++;  
  51.             }  
  52.         }  
  53.         endPosition = endPosition -1;  
  54.           
  55.         //设置保存文件上传的路径  
  56.         String realPath = getServletContext().getRealPath("/")+"images";  
  57.         System.out.println("保存文件上传的路径:"+realPath);  
  58.         File fileupload = new File(realPath);  
  59.         if(!fileupload.exists()){  
  60.             fileupload.mkdir();  //创建此抽象路径名指定的目录。   
  61.         }  
  62.         File saveFile = new File(realPath, fileName);  
  63.         RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");  
  64.         //从临时文件中读取文件内容(根据文件起止位置获取)  
  65.         randomFile.seek(startPosition);  
  66.         while(startPosition<endPosition){  
  67.             randomAccessFile.write(randomFile.readByte());  
  68.             startPosition = randomFile.getFilePointer();  
  69.         }  
  70.           
  71.         //关闭输入输出流  
  72.         randomAccessFile.close();  
  73.         randomFile.close();  
  74.         tempFile.delete();  
  75.               
  76.         request.setAttribute("result", "上传成功!");  
  77.         RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");  
  78.         dispatcher.forward(request, response);  
  79.     }</span>  

三、文件下载原理

1、step1:需要通过HttpServletResponse.setContentType方法设置Content-type头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的MIME类型,例如,“application/octet-stream”或“application/x-msdownload”等。

2、step2:需要通过HttpServletResponse.setHeader方法设置Content-Disposition头的值为“attachment;filename=文件名”。

3、step3:读取下载文件,调用HttpServletResponse.getOutputStream方法返回的OutputStream对象来向客户端写入附件文件内容。

[html]  view plain  copy
  1. <span style="font-size:18px;">public void doGet(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         //获取文件下载路径  
  4.         String path = getServletContext().getRealPath("/") + "images/";  
  5.         String filename = request.getParameter("filename");  
  6.         File file = new File(path + filename);  
  7.         if(file.exists()){  
  8.             //设置相应类型application/octet-stream  
  9.             response.setContentType("application/x-msdownload");  
  10.             //设置头信息  
  11.             response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");  
  12.             InputStream inputStream = new FileInputStream(file);  
  13.             ServletOutputStream ouputStream = response.getOutputStream();  
  14.             byte b[] = new byte[1024];  
  15.             int n ;  
  16.             while((n = inputStream.read(b)) != -1){  
  17.                 ouputStream.write(b,0,n);  
  18.             }  
  19.             //关闭流、释放资源  
  20.             ouputStream.close();  
  21.             inputStream.close();  
  22.         }else{  
  23.             request.setAttribute("errorResult", "文件不存在下载失败!");  
  24.             RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/01.jsp");  
  25.             dispatcher.forward(request, response);  
  26.         }  
  27.     }</span>  
JSP页面内容:

[html]  view plain  copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">  
  10.     <title>My JSP '01.jsp' starting page</title>  
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">      
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15.     <meta http-equiv="description" content="This is my page">  
  16.     <link rel="stylesheet" type="text/css" href="css/common.css" />  
  17.     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>  
  18.     <script type="text/javascript">  
  19.         $(function(){  
  20.             $(".thumbs a").click(function(){  
  21.                 var largePath=$(this).attr("href");  
  22.                 var largeAlt=$(this).attr("title");  
  23.                 $("#largeImg").attr({  
  24.                     src:largePath,  
  25.                     alt:largeAlt  
  26.                 });  
  27.                 return false;  
  28.             });  
  29.             $("#myfile").change(function(){  
  30.                 $("previewImg").attr("src","file:///"+$("#myfile").val());  
  31.             });  
  32.               
  33.             var la = $("#large");  
  34.             la.hide();  
  35.               
  36.             $("#previewImg").mousemove(function(e){  
  37.                 la.css({  
  38.                     top:e.pagey,  
  39.                     left:e.pagex  
  40.                 }).html('<img src="'+this.src+'" />');  
  41.             }).mouseout(function(){  
  42.                 la.hide();  
  43.             });  
  44.               
  45.         });  
  46.         /* function showPreview(obj){  
  47.             var str = obj.value;  
  48.             document.getElementById("previewImg").innerHTML=  
  49.                 "<img src='"+str+"'/>";  
  50.                 alert(document.getElementById("previewImg").innerHTML);  
  51.         } */  
  52.     </script>  
  53.   </head>  
  54.     
  55.   <body>  
  56.     <img id="previewImg" src="images/preview.jpg" width="80" height="80" />  
  57.   <form action="uploadServlet.do" method="post" enctype="multipart/form-data">  
  58.     请选择上传图片:<input type="file" id="myfile" name="myfile" onchange="showPreview(this)" />  
  59.     <input type="submit" value="提交"/>  
  60.   </form>  
  61.   下载<a href="downloadServlet.do?filename=hello.txt">hello.txt</a>   ${errorResult}  
  62.   <div id="large"></div>  
  63.   <!-- <form action="">  
  64.     请选择上传图片:<input type="file" id="myfile" name="myfile" onchange="showPreview(this)" />  
  65.     <div id="previewImg"></div>  
  66.   </form> -->  
  67.    <hr>  
  68.    <h2>图片预览</h2>  
  69.     <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>  
  70.     <p class="thumbs">  
  71.         <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>  
  72.         <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>  
  73.         <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>  
  74.         <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>  
  75.         <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>  
  76.     </p>  
  77.   </body>  
  78. </html>  
SmartUpload实现上传下载

使用非常简单,直接引入SmartUpload的jar文件就可以啦

[html]  view plain  copy
  1. <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.         //设置上传文件保存路径  
  4.         String filePath = getServletContext().getRealPath("/")+"images";  
  5.         File file = new File(filePath);  
  6.         if(!file.exists()){  
  7.             file.mkdir();  
  8.         }  
  9.         SmartUpload su = new SmartUpload();  
  10.         //初始化smartUpload  
  11.         su.initialize(getServletConfig(), request, response);  
  12.         //设置上传文件大小  
  13.         su.setMaxFileSize(1024*1024*10);  
  14.         //设置所有文件的大小  
  15.         su.setTotalMaxFileSize(102481024*100);  
  16.         //设置允许上传文件的类型  
  17.         su.setAllowedFilesList("txt,jpg,gif");  
  18.         String result = "上传能成功";  
  19.         try {  
  20.             //设置禁止上传文件类型  
  21.             su.setDeniedFilesList("jsp,rar");  
  22.             su.upload();  
  23.             int count = su.save(filePath);  
  24.             System.out.println("上传成功"+count+"文件!");  
  25.         } catch (Exception e) {  
  26.             result="上传文件失败!";  
  27. <span style="white-space:pre">            </span>if(e.getMessage().indexOf("1015")!=-1){<span style="white-space:pre">                </span>  
  28. <span style="white-space:pre">                </span>result = "上传文件失败:上传文件类型不正确!";  
  29. <span style="white-space:pre">            </span>}else if(e.getMessage().indexOf("1010")!=-1){  
  30. <span style="white-space:pre">                </span>result = "上传文件失败:上传文件类型不正确!";  
  31. <span style="white-space:pre">            </span>}else if(e.getMessage().indexOf("1105")!=-1){  
  32. <span style="white-space:pre">                </span>result = "上传文件失败:上传文件大小大于允许上传的最大值!";  
  33. <span style="white-space:pre">            </span>}else if(e.getMessage().indexOf("1110")!=-1){  
  34. <span style="white-space:pre">                </span>result = "上传文件失败:上传文件的总大小大于我们允许上传总大小的最大值!";  
  35. <span style="white-space:pre">            </span>}  
  36. <span style="white-space:pre">            </span>e.printStackTrace();  
  37.         }  
  38.         for(int i=0;i<su.getFiles().getCount();i++){  
  39. <span style="white-space:pre">            </span>com.jspsmart.upload.File tempFile = su.getFiles().getFile(i);  
  40. <span style="white-space:pre">            </span>System.out.println("表单当中name属性值:"+tempFile.getFieldName());  
  41. <span style="white-space:pre">            </span>System.out.println("上传文件名:"+tempFile.getFileName());  
  42. <span style="white-space:pre">            </span>System.out.println("上传文件的大小:"+tempFile.getSize());  
  43. <span style="white-space:pre">            </span>System.out.println("上传文件名拓展名:"+tempFile.getFileExt());  
  44. <span style="white-space:pre">            </span>System.out.println("上传文件的全名:"+tempFile.getFilePathName());  
  45. <span style="white-space:pre">        </span>}  
  46.         request.setAttribute("result",result);  
  47.         request.getRequestDispatcher("jsp/02.jsp").forward(request, response);  
  48.     }</span>  
jsp页面表单提交内容:
[html]  view plain  copy
  1. <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">  
  10.     <title>My JSP '02.jsp' starting page</title>  
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">      
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15.     <meta http-equiv="description" content="This is my page">  
  16.     <link rel="stylesheet" type="text/css" href="css/common.css" />  
  17.     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>  
  18.     <script type="text/javascript">  
  19.         $(function(){  
  20.             $(".thumbs a").click(function(){  
  21.                 var largePath=$(this).attr("href");  
  22.                 var largeAlt=$(this).attr("title");  
  23.                 $("#largeImg").attr({  
  24.                     src:largePath,  
  25.                     alt:largeAlt  
  26.                 });  
  27.                 return false;  
  28.             });  
  29.         });  
  30.     </script>  
  31.   </head>  
  32.   <body>  
  33.     <form action="smartUploadServlet.do" method="post" enctype="multipart/form-data">  
  34.         上传文件1:<input type="file" name="myfile1"/><br>  
  35.         上传文件2:<input type="file" name="myfile2"/><br>  
  36.         上传文件3:<input type="file" name="myfile3"/><br>  
  37.         <input type="submit" value="提交"> ${result}  
  38.     </form>  
  39.    <hr></span>  
[html]  view plain  copy
  1. <span style="font-size:18px;">  下载:<a href="smartDownloadServlet.do?filename=img5-lg.jpg">img5-lg.jpg</a>  
  2.    <hr>  
  3.    <h2>图片预览</h2>  
  4.     <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>  
  5.     <p class="thumbs">  
  6.         <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>  
  7.         <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>  
  8.         <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>  
  9.         <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>  
  10.         <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>  
  11.     </p>  
  12.   </body>  
  13. </html></span>  
[html]  view plain  copy
  1. <span style="font-size:18px;"><span style="background-color: rgb(255, 255, 255);">下载部分的代码</span></span>  

[html]  view plain  copy
  1. <span style="font-size:18px;">public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.             throws ServletException, IOException {  
  3.   
  4.         String filename = request.getParameter("filename");  
  5.         SmartUpload su = new SmartUpload();  
  6.         su.initialize(getServletConfig(), request, response);  
  7.         su.setContentDisposition(null);  
  8.         try {  
  9.             su.downloadFile("/images/"+filename);  
  10.         } catch (SmartUploadException e) {  
  11.             e.printStackTrace();  
  12.         }  
  13.     }</span>  

Struts2实现上传下载:

上传jsp页面代码:

[html]  view plain  copy
  1. <span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  7. <html>  
  8.   <head>  
  9.     <base href="<%=basePath%>">  
  10.     <title>My JSP '03.jsp' starting page</title>  
  11.     <meta http-equiv="pragma" content="no-cache">  
  12.     <meta http-equiv="cache-control" content="no-cache">  
  13.     <meta http-equiv="expires" content="0">      
  14.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  15.     <meta http-equiv="description" content="This is my page">  
  16.     <link rel="stylesheet" type="text/css" href="css/common.css" />  
  17.     <script type="text/javascript" src="js/jquery-1.11.1.js"></script>  
  18.     <script type="text/javascript">  
  19.         $(function(){  
  20.             $(".thumbs a").click(function(){  
  21.                 var largePath=$(this).attr("href");  
  22.                 var largeAlt=$(this).attr("title");  
  23.                 $("#largeImg").attr({  
  24.                     src:largePath,  
  25.                     alt:largeAlt  
  26.                 });  
  27.                 return false;  
  28.             });  
  29.         });  
  30.     </script>  
  31.   </head>  
  32.   <body>  
  33.     <h2> 文件上传</h2>  
  34.     <form action="upload.action" method="post" enctype="multipart/form-data">  
  35.         上传文件1:<input type="file" name="upload"/><br>  
  36.         上传文件2:<input type="file" name="upload"/><br>  
  37.         上传文件3:<input type="file" name="upload"/><br>  
  38.         <input type="submit" value="提交"> ${result}  
  39.     </form>  
  40.    <hr>  
  41.    <h2>图片预览</h2>  
  42.     <p><img id="largeImg" src="images/img1-lg.jpg" alt="Large Image"/></p>  
  43.     <p class="thumbs">  
  44.         <a href="images/img2-lg.jpg" title="Image2"><img src="images/img2-thumb.jpg"></a>  
  45.         <a href="images/img3-lg.jpg" title="Image3"><img src="images/img3-thumb.jpg"></a>  
  46.         <a href="images/img4-lg.jpg" title="Image4"><img src="images/img4-thumb.jpg"></a>  
  47.         <a href="images/img5-lg.jpg" title="Image5"><img src="images/img5-thumb.jpg"></a>  
  48.         <a href="images/img6-lg.jpg" title="Image6"><img src="images/img6-thumb.jpg"></a>  
  49.     </p>  
  50.   </body>  
  51. </html></span>  
struts.xml部分代码

[html]  view plain  copy
  1. <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5. <struts>  
  6.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  7.     <constant name="struts.devMode" value="true" />  
  8.     <!-- 国际化 -->  
  9.     <constant name="struts.custom.i18n.resources" value="app"></constant>  
  10.     <package name="default" namespace="/" extends="struts-default">  
  11.             <action name="upload" class="com.lihf.action.FileUploadAction">  
  12.                     <result>/jsp/03.jsp</result>  
  13.                     <result name="input">/jsp/error.jsp</result>  
  14.                     <!-- 配置拦截器限制上传文件类型及大小 -->  
  15.                     <interceptor-ref name="fileUpload">  
  16.                         <param name="allowedTypes">image/bmp,image/x-png,image/gif,image/pjpeg</param>  
  17.                         <param name="maximumSize">2M</param>  
  18.                     </interceptor-ref>  
  19.                     <interceptor-ref name="defaultStack"></interceptor-ref>  
  20.             </action>  
  21.             <action name="download" class="com.lihf.action.DownLoadAction">  
  22.                 <param name="inputPath">/images/img2-lg.jpg</param>  
  23.                 <result name="success" type="stream">  
  24.                     <param name="contentType">application/octet-stream</param>  
  25.                     <param name="inputName">inputStream</param>  
  26.                     <!-- 以附件的形式下载 -->  
  27.                     <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>  
  28.                     <param name="bufferSize">8192</param>  
  29.                 </result>  
  30.             </action>  
  31.     </package>  
  32. </struts></span>  
web.xml部分代码

[html]  view plain  copy
  1. <span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  3.   <display-name>scxz</display-name>  
  4.   <servlet>  
  5.     <servlet-name>UploadServlet</servlet-name>  
  6.     <servlet-class>com.lihf.servlet.UploadServlet</servlet-class>  
  7.   </servlet>  
  8.   <servlet>  
  9.     <servlet-name>DownloadServlet</servlet-name>  
  10.     <servlet-class>com.lihf.servlet.DownloadServlet</servlet-class>  
  11.   </servlet>  
  12.   <servlet>  
  13.     <servlet-name>SmartUploadServlet</servlet-name>  
  14.     <servlet-class>com.lihf.servlet.SmartUploadServlet</servlet-class>  
  15.   </servlet>  
  16.   <servlet>  
  17.     <servlet-name>SmartDownloadServlet</servlet-name>  
  18.     <servlet-class>com.lihf.servlet.SmartDownloadServlet</servlet-class>  
  19.   </servlet>  
  20.   <servlet-mapping>  
  21.     <servlet-name>UploadServlet</servlet-name>  
  22.     <url-pattern>/uploadServlet.do</url-pattern>  
  23.   </servlet-mapping>  
  24.   <servlet-mapping>  
  25.     <servlet-name>DownloadServlet</servlet-name>  
  26.     <url-pattern>/downloadServlet.do</url-pattern>  
  27.   </servlet-mapping>  
  28.   <servlet-mapping>  
  29.     <servlet-name>SmartUploadServlet</servlet-name>  
  30.     <url-pattern>/smartUploadServlet.do</url-pattern>  
  31.   </servlet-mapping>  
  32.   <servlet-mapping>  
  33.     <servlet-name>SmartDownloadServlet</servlet-name>  
  34.     <url-pattern>/smartDownloadServlet.do</url-pattern>  
  35.   </servlet-mapping>  
  36.   <filter>  
  37.     <filter-name>struts2</filter-name>  
  38.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  39.   </filter>  
  40.   <filter-mapping>  
  41.       <filter-name>struts2</filter-name>  
  42.       <url-pattern>/*</url-pattern>  
  43.   </filter-mapping>  
  44.   <welcome-file-list>  
  45.     <welcome-file>index.jsp</welcome-file>  
  46.   </welcome-file-list>  
  47. </web-app></span>  
action方法:

[html]  view plain  copy
  1. <span style="font-size:18px;">package com.lihf.action;  
  2.   
  3. import java.io.File;  
  4. import java.util.List;  
  5.   
  6. import org.apache.commons.io.FileUtils;  
  7. import org.apache.struts2.ServletActionContext;  
  8.   
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. public class FileUploadAction extends ActionSupport {  
  12.   
  13.     private List<File> upload;  
  14.     private List<String> uploadContentType;  
  15.     private List<String> uploadFileName;  
  16.     private String result;  
  17.     public List<File> getUpload() {  
  18.         return upload;  
  19.     }  
  20.     public void setUpload(List<File> upload) {  
  21.         this.upload = upload;  
  22.     }  
  23.     public List<String> getUploadContentType() {  
  24.         return uploadContentType;  
  25.     }  
  26.     public void setUploadContentType(List<String> uploadContentType) {  
  27.         this.uploadContentType = uploadContentType;  
  28.     }  
  29.     public List<String> getUploadFileName() {  
  30.         return uploadFileName;  
  31.     }  
  32.     public void setUploadFileName(List<String> uploadFileName) {  
  33.         this.uploadFileName = uploadFileName;  
  34.     }  
  35.     public String getResult() {  
  36.         return result;  
  37.     }  
  38.     public void setResult(String result) {  
  39.         this.result = result;  
  40.     }  
  41.     @Override  
  42.     public String execute() throws Exception {  
  43.         String path = ServletActionContext.getServletContext().getRealPath("/images");  
  44.         File file = new File(path);  
  45.         if(!file.exists()){  
  46.             file.mkdir();  
  47.         }  
  48.         for(int i=0;i<upload.size();i++){              
  49.             FileUtils.copyFile(upload.get(i), new File(file,uploadFileName.get(i)));  
  50.         }  
  51.         result ="上传成功!";  
  52.         return SUCCESS;  
  53.     }  
  54.   
  55. }  
  56. </span>  
下载:

action方法:

[html]  view plain  copy
  1. <span style="font-size:18px;">package com.lihf.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.net.URLEncoder;  
  8.   
  9. import org.apache.commons.io.FileUtils;  
  10. import org.apache.struts2.ServletActionContext;  
  11.   
  12. import com.opensymphony.xwork2.ActionSupport;  
  13.   
  14. public class DownLoadAction extends ActionSupport {  
  15.     public String inputPath;  
  16.     public String fileName;  
  17.     public String getFileName() {  
  18.         return fileName;  
  19.     }  
  20.     public void setFileName(String fileName) {  
  21.         this.fileName = fileName;  
  22.     }  
  23.     public String getInputPath() {  
  24.         return inputPath;  
  25.     }  
  26.     public void setInputPath(String inputPath) {  
  27.         this.inputPath = inputPath;  
  28.     }  
  29.     @Override  
  30.     public String execute() throws Exception {  
  31.         return SUCCESS;  
  32.     }  
  33.     public InputStream getInputStream() throws IOException{  
  34.         String path = ServletActionContext.getServletContext().getRealPath("/images");  
  35.         String filePath = path+"\\"+fileName;  
  36.         File file = new File(filePath);  
  37.         return FileUtils.openInputStream(file);  
  38.         //根据文件路径获取流信息固定下载文件使用方法  
  39.         //return ServletActionContext.getServletContext().getResourceAsStream(inputPath);  
  40.     }  
  41.     public String getDownloadFileName(){  
  42.         //如果是中文的文件名称需要转码  
  43.         String downloadFileName = "";  
  44.         try {  
  45.             downloadFileName = URLEncoder.encode("文件下载.jpg","UTF-8");  
  46.         } catch (UnsupportedEncodingException e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.         return downloadFileName;  
  50.     }  
  51. }  
  52. </span>  
jsp页面:

<a href="download.action?fileName=img3-lg.jpg">文件下载(图片)</a>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值