1、 servlet 如何实现文件的上传和下载?
1.1上传文件
参考自:http://blog.csdn.net/hzc543806053/article/details/7524491
通过前台选择文件,然后将资源上传到(即新建一个文件)到发布的资源文件下面,
在开始JSP上传文件之前你要准备以下几个东西:
1. commons-FileUpload 1.3 包
下载地址:http://jakarta.apache.org/commons/fileupload/
2. commons-IO 2.5 包
下载地址:http://jakarta.apache.org/commons/io/
有了上面这些东西我们就可以开始了
1. 新建一个叫Servlet_UploadDownLoad的WEB项目
2. 接着把这两个jar包放到WEB-INF/lib目录中:
3.接下来我们要准备一份如下内容的upload.jsp文件,用来选择要上传的文件,
- <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Jsp+Servlet upload file</title>
- </head>
- <body>
- <form action="UploadServlet" method="POST" enctype="multipart/form-data">
- <input type ="file" name="file1" id="file1"/><br/>
- <input type ="file" name="file2" if="file2"/><br/>
- <input type ="file" name="file3" id="file3"/><br/>
- <input type="submit" value="Submit" /><br/>
- <input type="reset" />
- </form>
- </body>
- </html>
上面文件中有几个需要注意的地方就是
1. action="UploadServlet" 必须和后面的web.xml配置文件中对servlet映射必须保持一致.
2. method="POST" 这里必须为"POST"方式提交不能是"GET".
3. enctype="multipart/form-data" 这里是要提交的内容格式,表示你要提交的是数据流,而不是普通的表单文本.
4. file1,file2,file3表示你要3个文件一起上传,你也可以一次只上传一个文件.
接下来我们要写一个与上面这个upload.jsp配套的servlet程序,就叫做UploadServlet.java吧
- import java.io.File;
- import java.io.*;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- /**
- *
- * @author Administrator 文件上传 具体步骤: 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包 2) 利用
- * request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同 3)对
- * DiskFileItemFactory 对象设置一些 属性 4)高水平的API文件上传处理 ServletFileUpload
- * upload = new ServletFileUpload(factory); 目的是调用
- * parseRequest(request)方法 获得 FileItem 集合list ,
- *
- * 5)在 FileItem 对象中 获取信息, 遍历, 判断 表单提交过来的信息 是否是 普通文本信息 另做处理 6) 第一种. 用第三方
- * 提供的 item.write( new File(path,filename) ); 直接写到磁盘上 第二种. 手动处理
- *
- */
- public class UploadServlet extends HttpServlet {
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("utf-8"); // 设置编码
- // 获得磁盘文件条目工厂
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // 获取文件需要上传到的路径
- String path = request.getRealPath("/uploadFile");
- // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
- // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
- /**
- * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
- * 格式的 然后再将其真正写到 对应目录的硬盘上
- */
- factory.setRepository(new File(path));
- // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
- factory.setSizeThreshold(1024 * 1024);
- // 高水平的API文件上传处理
- ServletFileUpload upload = new ServletFileUpload(factory);
- try {
- // 可以上传多个文件
- List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
- for (FileItem item : list) {
- // 获取表单的属性名字
- String name = item.getFieldName();
- // 如果获取的 表单信息是普通的 文本 信息
- if (item.isFormField()) {
- // 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
- String value = item.getString();
- request.setAttribute(name, value);
- } else {// 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
- /**
- * 以下三步,主要获取 上传文件的名字
- */
- // 获取路径名
- String value = item.getName();
- // 索引到最后一个反斜杠
- int start = value.lastIndexOf("\\");
- // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
- String filename = value.substring(start + 1);
- request.setAttribute(name, filename);
- // 真正写到磁盘上
- // 它抛出的异常 用exception 捕捉
- // item.write( new File(path,filename) );//第三方提供的
- // 手动写的
- OutputStream out = new FileOutputStream(new File(path,
- filename));
- InputStream in = item.getInputStream();
- int length = 0;
- byte[] buf = new byte[1024];
- System.out.println("获取上传文件的总共的容量:" + item.getSize());
- // in.read(buf) 每次读到的数据存放在 buf 数组中
- while ((length = in.read(buf)) != -1) {
- // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
- out.write(buf, 0, length);
- }
- in.close();
- out.close();
- }
- }
- } catch (FileUploadException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- // e.printStackTrace();
- }
- }
- }
upload.jsp文件有了,配套的servlet也有了,现在最后剩下的就是怎么让它们配合工作了,接着我们把WEB-INF/web.xml文件请出来,并在该文件中加入以下内容:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>upload.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>UploadServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/UploadServlet</url-pattern>
- </servlet-mapping>
- </web-app>
写好以后再点击"保存"
把你的upload项目整个拷贝到tomcat的webapps目录下,启动tomcat.打开IE浏览器在地址栏中输入http://localhost:8080/Servlet_UploadDownLoad/upload.jsp怎么样看到JSP上传文件的输入框了吗? 什么,没有看到,出错了! 你仔细检查一下步骤有没有对.
好了,现在我们点击页面上的"浏览"按钮,找到我们要上传的文件,最后点击"Submit",太激动了,还不看一下你的I:\\updir里面有没有你要的东西.
1.2下载文件
1)通过超链接实现下载
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <meta charset="UTF-8">
- <title>通过链接下载文件</title>
- </head>
- <body>
- <h1>通过链接下载文件</h1>
- <a href="/Servlet_UploadDownLoad/file/commons-beanutils-1.9.3-bin.zip">压缩包</a>
- <a href="/Servlet_UploadDownLoad/file/Koala.jpg">图片</a>
- </body>
- </html>
"/Servlet_UploadDownLoad/file/commons-beanutils-1.9.3-bin.zip"是文件路径,程序结构如下图:
程序运行后,可以通过单击需要下载文档实现下载
但是这里会出现一个问题,就是单击下载压缩包的时候会弹出下载页面,但是下载图片的时候浏览器就直接打开了图片,没有下载。
这是因为通过超链接下载文件时,如果浏览器可以识别该文件格式,浏览器就会直接打开。只有浏览器不能识别该文件格式的时候,才会实现下载。
因此利用第二种方法实现下载功能。
2)通过Servlet程序实现下载
通过Servlet下载文件的原理是通过servlet读取目标程序,将资源返回客户端。
downloadTwo.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <meta charset="UTF-8">
- <title>通过链接下载文件</title>
- </head>
- <body>
- <h1>通过链接下载文件</h1>
- <a href="/Servlet_UploadDownLoad/file/commons-beanutils-1.9.3-bin.zip">压缩包</a>
- <a href="/Servlet_UploadDownLoad/file/Koala.jpg">图片</a>
- <h1>通过servlet程序下载文件</h1>
- <a href="/Servlet_UploadDownLoad/ServletDownload?filename=commons-beanutils-1.9.3-bin.zip">压缩包</a>
- <a href="/Servlet_UploadDownLoad/ServletDownload?filename=Koala.jpg">图片</a>
- </body>
- </html>
web.xml :
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>upload.jsp</welcome-file>
- </welcome-file-list>
- <servlet>
- <servlet-name>UploadServlet</servlet-name>
- <servlet-class>UploadServlet</servlet-class>
- </servlet>
- <servlet>
- <description>ServletDownload</description>
- <display-name>ServletDownload</display-name>
- <servlet-name>ServletDownload</servlet-name>
- <servlet-class>ServletDownload</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadServlet</servlet-name>
- <url-pattern>/UploadServlet</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>ServletDownload</servlet-name>
- <url-pattern>/ServletDownload</url-pattern>
- </servlet-mapping>
- </web-app>
ServletDownload.java :
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class ServletDownload extends HttpServlet {
- /**
- * Constructor of the object.
- */
- public ServletDownload() {
- super();
- }
- /**
- * The doGet method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //获得请求文件名
- String filename = request.getParameter("filename");
- System.out.println(filename);
- //设置文件MIME类型
- response.setContentType(getServletContext().getMimeType(filename));
- //设置Content-Disposition
- response.setHeader("Content-Disposition", "attachment;filename="+filename);
- //读取目标文件,通过response将目标文件写到客户端
- //获取目标文件的绝对路径
- String fullFileName = getServletContext().getRealPath("/file/" + filename);
- //System.out.println(fullFileName);
- //读取文件
- InputStream in = new FileInputStream(fullFileName);
- OutputStream out = response.getOutputStream();
- //写文件
- int b;
- while((b=in.read())!= -1)
- {
- out.write(b);
- }
- in.close();
- out.close();
- }
- /**
- * The doPost method of the servlet. <br>
- *
- * This method is called when a form has its tag value method equals to post.
- *
- * @param request the request send by the client to the server
- * @param response the response send by the server to the client
- * @throws ServletException if an error occurred
- * @throws IOException if an error occurred
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- }
- }
重启tomcat服务器,即可实现对压缩包和对图片的下载。
2、struts如何实现文件的上传和下载?
2.1struts上传文件
先新建web project ,然后Add Struts Capabilties:
struts.xml 的配置:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <!--使用Struts2进行文件上传的时候,Struts2默认文件大小最大为2MB,如果要传大一点的文件,就需要修改struts.xml配置文件,重新设置能够上传的最大的文件大小。-->
- <!-- Struts2全局配置 -->
- <!-- 修改上传的最大文件大小:100MB -->
- <constant name="struts.multipart.maxSize" value="104857600"/>
- <package name="upload" extends="struts-default">
- <!-- 文件上传的拦截器栈 (只允许上传图片文件)-->
- <interceptors>
- <interceptor-stack name="fileUploadStack">
- <interceptor-ref name="fileUpload">
- <param name="allowedTypes">image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg</param>
- </interceptor-ref>
- <interceptor-ref name="basicStack" />
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="fileUploadStack"></default-interceptor-ref>
- <action name="upload" class="com.action.UploadAction.UploadAction">
- <result name="success">/success.jsp</result>
- <result name="input">/upload.jsp</result>
- <interceptor-ref name="fileUploadStack"></interceptor-ref>
- </action>
- </package>
- </struts>
upload.jsp :
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Jsp+Struts2 upload file</title>
- </head>
- <body>
- <h1 style="color: red;">【请选择图片进行上传】</h1>
- <form action="upload.action" theme="simple" enctype="multipart/form-data" method="post">
- <input type ="file" name="file"/><br/>
- <input type ="file" name="file"/><br/>
- <input type ="file" name="file"/><br/>
- <input type="submit" value="Submit" /><br/>
- <input type="reset" />
- </form>
- </body>
- </html>
<form action="upload.action" theme="simple" enctype="multipart/form-data" method="post">
theme="simple"是struts2 的一个最简单的主题,这样你的标签就生成最简单的HTML元素 不会生成额外的内容
<input type="file" name="file" />
【这里的name一定要与action类里面的name名字一致,set/get】
success.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>上传图片成功 </title>
- </head>
- <body>
- 上传图片成功 !!!<br>
- </body>
- </html>
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <display-name></display-name>
- <welcome-file-list>
- <welcome-file>upload.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
UploadAction.java
- package com.action.UploadAction;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import com.file.util.Upload;
- import com.opensymphony.xwork2.ActionSupport;
- public class UploadAction extends ActionSupport {
- private List<File> file;
- private List<String> fileFileName;
- private List<String> fileContentType;
- public List<File> getFile() {
- return file;
- }
- public void setFile(List<File> file) {
- this.file = file;
- }
- public List<String> getFileFileName() {
- return fileFileName;
- }
- public void setFileFileName(List<String> fileFileName) {
- this.fileFileName = fileFileName;
- }
- public List<String> getFileContentType() {
- return fileContentType;
- }
- public void setFileContentType(List<String> fileContentType) {
- this.fileContentType = fileContentType;
- }
- @Override
- public String execute() throws Exception {
- Upload upload = new Upload();
- ArrayList list = upload.upload(file, this.getFileFileName(), "/files/");
- if (list.size() > 0) {
- return SUCCESS;
- }else {
- return INPUT;
- }
- }
- }
Upload.java
- package com.file.util;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import org.apache.struts2.ServletActionContext;
- public class Upload {
- @SuppressWarnings("unchecked")
- /*
- * @file:文件域列表
- *
- * @fileName:上传文件的文件名
- *
- * @path:文件上传的目录,相对目录。 说明:文件上传所存放目录的规则:网站根目录下 files/会员ID/网站类型名称/上传文件分类名称/
- *
- * @返回结果:一个存放上传文件所在位置相对路径的ArrayList
- */
- public ArrayList upload(List file, List fileName, String path)
- throws IOException {
- // String root = ServletActionContext.getRequest().getRealPath(path);
- String root = ServletActionContext.getServletContext()
- .getRealPath(path);
- File dir = new File(root);
- if (dir.exists() == false) {
- dir.mkdirs();
- }
- ArrayList list = new ArrayList();
- for (int i = 0; i < file.size(); ++i) {
- InputStream is = new FileInputStream(file.get(i).toString());
- /*
- * SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");//
- * 格式化时间输出 String Rname = sdf.format(new Date());//
- * 取得当前时间,Date()是java.util包里的,这作为真实名称 name = Rname + name;//
- * 重命名文件名称,命名规则为:时间+原文件名称
- */
- String name = fileName.get(i).toString();// 得到上传文件的原名称
- File destFile = new File(root, name);
- OutputStream os = new FileOutputStream(destFile);
- byte[] buffer = new byte[400];
- int length = 0;
- while ((length = is.read(buffer)) > 0) {
- os.write(buffer, 0, length);
- }
- list.add(path + name);
- is.close();
- os.close();
- }
- return list;
- }
- }
mkdirs()可以建立多级文件夹, mkdir()只会建立一级的文件夹, 如下:
new File("/tmp/one/two/three").mkdirs();
执行后, 会建立tmp/one/two/three四级目录
new File("/tmp/one/two/three").mkdir();
则不会建立任何目录, 因为找不到/tmp/one/two目录, 结果返回false
例子的代码结构:
2.2struts下载文件
方法一:通过配置struts.xml文件
DownloadAction.java
- package com.action.DownloadAction;
- import java.io.InputStream;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- //文件下载
- public class DownloadAction extends ActionSupport {
- private String fileName;
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- // 返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流
- public InputStream getDownloadFile() throws Exception {
- //解决中文乱码,get方式提交的参数编码,只支持iso8859-1编码,UTF-8是前台jsp页面的编码格式
- this.fileName = new String(this.fileName.getBytes("ISO-8859-1"), "UTF-8");
- String path = "downloadFile/"+this.fileName;//要下载的文件路径
- //重新转换成ISO-8859-1,下载文件的时候展示的文件名
- this.fileName = new String(this.fileName.getBytes("UTF-8"), "ISO-8859-1");
- return ServletActionContext.getServletContext().getResourceAsStream(path);
- }
- public String execute() throws Exception {
- return SUCCESS;
- }
- }
struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <!--使用Struts2进行文件上传的时候,Struts2默认文件大小最大为2MB,如果要传大一点的文件,就需要修改struts.xml配置文件,重新设置能够上传的最大的文件大小。-->
- <!-- Struts2全局配置 -->
- <!-- 修改上传的最大文件大小:100MB -->
- <constant name="struts.multipart.maxSize" value="104857600"/>
- <package name="upload" extends="struts-default">
- <!-- 文件上传的拦截器栈 (只允许上传图片文件)-->
- <interceptors>
- <interceptor-stack name="fileUploadStack">
- <interceptor-ref name="fileUpload">
- <param name="allowedTypes">image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg</param>
- </interceptor-ref>
- <interceptor-ref name="basicStack" />
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="fileUploadStack"></default-interceptor-ref>
- <action name="upload" class="com.action.UploadAction.UploadAction">
- <result name="success">/success.jsp</result>
- <result name="input">/upload.jsp</result>
- <interceptor-ref name="fileUploadStack"></interceptor-ref>
- </action>
- </package>
- <package name="download" extends="struts-default">
- <action name="download" class="com.action.DownloadAction.DownloadAction">
- <result name="success" type="stream">
- <param name="contentType">text/plain</param>
- <param name="contentDisposition">attachment;fileName="${fileName}"</param>
- <param name="inputName">DownloadFile</param>
- <param name="bufferSize">1024</param>
- </result>
- </action>
- </package>
- </struts>
1.结果类型必须要写成 type="stream" ,与之对应的处理类是 org.apache.struts2.dispatcher.StreamResult
2.涉及到的参数:
3.
1) <param name="contentDisposition">attachment;fileName="${fileName}"</param>
contentDisposition默认是 inline(内联的), 比如说下载的文件是文本类型的,就直接在网页上打开,不能直接打开的才会打开下载框自己选择
2) attachment :下载时会打开下载框
3) fileName="${fileName}" :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字
4.<param name="inputName">DownloadFile</param>,这个DownloadFile名字要和DownloadAction.java类中的getDownloadFile()方法名去掉get 一致
Struts2下载文件实现的说明
contentType
内容类型,和互联网MIME标准中的规定类型一致,例如text/plain代表纯文本,text/xml表示XML,image/gif代表GIF图片,image/jpeg代表JPG图片
inputName
下载文件的来源流,对应着action类中某个类型为Inputstream的属性名,例如取值为inputStream的属性需要编写getInputStream()方法
contentDisposition
文件下载的处理方式,包括内联(inline)和附件(attachment)两种方式,而附件方式会弹出文件保存对话框,否则浏览器会尝试直接显示文件。取值为:
attachment;filename="struts2.txt",表示文件下载的时候保存的名字应为struts2.txt。如果直接写filename="struts2.txt",那么默认情况是代表inline,浏览器会尝试自动打开它,等价于这样的写法:inline;filename="struts2.txt"
bufferSize
下载缓冲区的大小
downloadOne.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts下载文件</title>
- </head>
- <body>
- <h2>文件下载内容:</h2><br/>
- 1.jpg:<a href="download.action?fileName=1.jpg">点击下载</a><br/>
- 2.jpg:<a href="download.action?fileName=2.jpg">点击下载2</a><br/>
- 中文1.jpg:<a href="download.action?fileName=中文1.jpg">点击下载中文1.jpg</a><br/>
- 中文2.jpg:<a href="download.action?fileName=中文2.jpg">点击下载中文2.jpg</a><br/>
- </body>
- </html>
例子的代码结构:
方法二
方法二:通过配置java文件来实现下载
DownloadByJavaAction.java
- package com.action.DownloadAction;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class DownloadByJavaAction extends ActionSupport {
- private String fileName;
- public String getFileName() {
- return fileName;
- }
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
- public void download() throws Exception{
- /**
- * 配置文件路径
- */
- String realPath = ServletActionContext.getRequest().getRealPath("/");
- String path = getText("/downloadFile/");
- //解决中文乱码,get方式提交的参数编码,只支持iso8859-1编码,UTF-8是前台jsp页面的编码格式
- fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
- File file = new File(realPath+path+fileName);
- InputStream in = new FileInputStream(file);
- //重新转换成ISO-8859-1,下载文件的时候展示的文件名
- fileName = new String(this.fileName.getBytes("UTF-8"), "ISO-8859-1");
- /**
- * 配置下载参数,下载文件
- */
- BufferedInputStream input = null;
- BufferedOutputStream output = null;
- try {
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setCharacterEncoding("utf-8");
- response.setContentType("application/x-download");// 设置为下载application/x-download
- response.addHeader("content-type", "application/x-msdownload");
- response.setHeader("Content-Disposition", "attachment; filename="
- + fileName);
- response.setContentType("application/octet-stream");
- input = new BufferedInputStream(in);
- output = new BufferedOutputStream(response.getOutputStream());
- byte[] buff = new byte[4096];
- int n = 0;
- while ((n = input.read(buff)) != -1) {
- output.write(buff, 0, n);
- }
- output.flush();
- } catch (Exception e) {
- } finally {
- try {
- if (output != null) {
- output.close();
- output = null;
- }
- if (input != null) {
- input.close();
- input = null;
- }
- if (in != null) {
- in.close();
- in = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
downloadByJava.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts下载文件(java实现)</title>
- </head>
- <body>
- <h2 style="color:red;">JAVA实现</h2>
- <h2>文件下载内容:</h2><br/>
- 1.jpg:<a href="downloadByJava!download.action?fileName=1.jpg">点击下载</a><br/>
- 2.jpg:<a href="downloadByJava!download.action?fileName=2.jpg">点击下载2</a><br/>
- 中文1.jpg:<a href="downloadByJava!download.action?fileName=中文1.jpg">点击下载中文1.jpg</a><br/>
- 中文2.jpg:<a href="downloadByJava!download.action?fileName=中文2.jpg">点击下载中文2.jpg</a><br/>
- </body>
- </html>
struts.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <!--使用Struts2进行文件上传的时候,Struts2默认文件大小最大为2MB,如果要传大一点的文件,就需要修改struts.xml配置文件,重新设置能够上传的最大的文件大小。-->
- <!-- Struts2全局配置 -->
- <!-- 修改上传的最大文件大小:100MB -->
- <constant name="struts.multipart.maxSize" value="104857600"/>
- <package name="upload" extends="struts-default">
- <!-- 文件上传的拦截器栈 (只允许上传图片文件)-->
- <interceptors>
- <interceptor-stack name="fileUploadStack">
- <interceptor-ref name="fileUpload">
- <param name="allowedTypes">image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg</param>
- </interceptor-ref>
- <interceptor-ref name="basicStack" />
- </interceptor-stack>
- </interceptors>
- <default-interceptor-ref name="fileUploadStack"></default-interceptor-ref>
- <action name="upload" class="com.action.UploadAction.UploadAction">
- <result name="success">/success.jsp</result>
- <result name="input">/upload.jsp</result>
- <interceptor-ref name="fileUploadStack"></interceptor-ref>
- </action>
- </package>
- <package name="download" extends="struts-default">
- <!-- 通过配置struts.xml文件实现下载 -->
- <action name="download" class="com.action.DownloadAction.DownloadAction">
- <result name="success" type="stream">
- <param name="contentType">text/plain</param>
- <param name="contentDisposition">attachment;fileName="${fileName}"</param>
- <param name="inputName">DownloadFile</param>
- <param name="bufferSize">1024</param>
- </result>
- </action>
- <!-- 通过配置JAVA文件来实现下载 -->
- <action name="downloadByJava"
- class="com.action.DownloadAction.DownloadByJavaAction">
- </action>
- </package>
- </struts>
程序目录结构:
3、批量下载
使用多线程并发调用单个文件的下载方法即可。
4、断点续传
有待研究。。。。。。。。。。
附件源码:
Servlet实现文件的上传下载:https://gitee.com/KingXin666/Servlet_UploadDownLoad/tree/master/Servlet_UploadDownLoad
Struts2实现文件的上传下载:https://gitee.com/KingXin666/Struts2_UploadDownload