javaweb文件下载
最近搞了一下struts文件上传下载了,一个是通过struts自带的类实现的下载方法,一个是通用的下载方法:
struts实现:
FileDownloadAction.java
package com.fro.action; import java.io.FileInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import com.opensymphony.xwork2.ActionSupport; public class FileDownloadAction extends ActionSupport implements ServletRequestAware, ServletResponseAware { /** * */ private static final long serialVersionUID = 1L; private HttpServletRequest request; private HttpServletResponse response; private int number; private String fileName; private String contentType; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getFileName() { return fileName; } public void setFileName(String fileName) throws UnsupportedEncodingException { this.fileName = fileName; } public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } // 返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流 public InputStream getDownloadFile() { try { if (1 == number) { this.fileName = "使用说明书.doc"; // 解决文件乱码问题 if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器 } else { fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器 } this.contentType = "application/msword"; // 获取资源路径 return ServletActionContext.getServletContext().getResourceAsStream("files/使用说明书.doc"); } else if (2 == number) { this.fileName = "ModbusV2.0_down.mp4"; // 解决文件乱码问题 if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器 } else { fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器 } this.contentType = "video/mp4"; // 获取资源路径 return ServletActionContext.getServletContext().getResourceAsStream("mediaelement/media/ModbusV2.0_down.mp4"); } } catch (Exception e) { e.printStackTrace(); return null; } return null; } @Override public String execute() throws Exception { return SUCCESS; } @Override public void setServletResponse(HttpServletResponse response) { this.response = response; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } }
struts.xml文件配置:
<action name="FileDownload" class="com.fro.action.FileDownloadAction"> <result name="success" type="stream"> <param name="contentType">${contentType}</param> <param name="contentDisposition">attachment;fileName="${fileName}"</param> <param name="inputName">downloadFile</param> <param name="bufferSize">1024</param> </result> </action>
下面是通用的下载方法,不过我这里还是用struts实现的:
DdownloadAction.java
package com.fro.action; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.interceptor.ServletRequestAware; import org.apache.struts2.interceptor.ServletResponseAware; import com.opensymphony.xwork2.ActionSupport; public class DdownloadAction extends ActionSupport implements ServletRequestAware, ServletResponseAware { /** * */ private static final long serialVersionUID = 1L; private String contentType;// 文件类型 private String filename;// 指定下载后的文件名 private HttpServletRequest request; private HttpServletResponse response; public InputStream getTargetFile() throws Exception { String realPath = request.getSession().getServletContext().getRealPath("/"); String filePath = realPath + "/mediaelement/media/ModbusV2.0_down.mp4"; System.out.println("filePath:" + filePath); File file = new File(filePath); response.setContentType("application/octet-stream; charset=UTF-8"); String fileName = "ModbusV2.0_down.mp4"; // 解决中文文件名乱码问题 if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) { fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器 } else { fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器 } response.setHeader("Content-Disposition", "attachment;filename=" + fileName); InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] data = new byte[1024]; int len = 0; while ((len = in.read(data)) != -1) { out.write(data, 0, len); } out.flush(); return null; } public String execute() throws Exception { return SUCCESS; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public HttpServletRequest getRequest() { return request; } public void setRequest(HttpServletRequest request) { this.request = request; } public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } @Override public void setServletResponse(HttpServletResponse response) { response.setCharacterEncoding("utf-8"); this.response = response; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } }
struts.xml文件配置:
<action name="download_*" class="com.fro.action.DdownloadAction" method="{1}"> <result name="success" type="redirect">/index.jsp</result> </action>
下面是我的jsp文件:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>My JSP 'filedownload.jsp' starting page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h2>文件下载内容:</h2> <br /> 使用说明书.doc: <a href="FileDownload.action?number=1">点击下载</a> <br /> ModbusV2.0_down.mp4: <a href="FileDownload.action?number=2">点击下载</a> <br /> 使用说明书.doc: <a href="download_getTargetFile.action">点击下载</a> <br /> 使用说明书.doc: <a href="file_download.action">点击下载</a> </body> </html>
其中解决了下载文件文件名中文乱码问题。
其他方式:
//判断是否为火狐浏览器 String Agent = request.getHeader("User-Agent"); StringTokenizer st = new StringTokenizer(Agent,";"); st.nextToken(); //得到用户的浏览器类型 String userbrowser = st.nextToken(); //LOGGER.debug(userbrowser+"浏览器---------------------------"); //LOGGER.debug(userbrowser.trim().toLowerCase()+"浏览器类型---------------------------"); //LOGGER.debug(userbrowser.trim().toLowerCase().contains("wow64)")+"是否为火狐浏览器----------------------------"); if(userbrowser.toLowerCase().contains("wow64")){ response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("GB2312"),"ISO-8859-1")); }else{ response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8")); }