public @ResponseBody void exportExcel(HttpServletRequest request, HttpServletResponse response, KhxxCxVO vo) throws IOException{ File csvFile = createCSVFile(request,vo);//獲取要下載的文件 BufferedInputStream bis = null; BufferedOutputStream bos = null; response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(csvFile.getName(), "UTF-8")); response.setHeader("Content-Length", String.valueOf(csvFile.length())); bis = new BufferedInputStream(new FileInputStream(csvFile)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; while (true) { int bytesRead; if (-1 == (bytesRead = bis.read(buff, 0, buff.length))) break; bos.write(buff, 0, bytesRead); } bis.close(); bos.close(); }
經常遇到選擇多個文件進行批量下載的情況,可以先將選擇的所有的文件生成一個zip文件,然后再下載,該zip文件,即可實現批量下載,但是在打包過程 中,常常也會出現下載過來的zip文件中里面有亂碼的文件名,通過使用ant.jar中的org.apache.tools.zip里的 ZipOutPutStream為實現編碼的設置。
代碼如下:
ant包引用
<dependency> <groupId>ant</groupId> <artifactId>ant</artifactId> <version>1.6.5</version> </dependency>
壓縮下載的action代碼
package demo.action; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; 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.net.URLEncoder; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts2.ServletActionContext; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import com.opensymphony.xwork2.ActionSupport; /** * 批量下載文件: * 使用ant.jar包中的org.apache.tools.zip.*完成壓縮, * java原生也有java.util.zip.*但是測試了下無法搞定壓縮 * 文件內文件名的中文問題 * @author yangcong * */ public class BatchDownloadAction extends ActionSupport { private Logger Log = Logger.getLogger(BatchDownloadAction.class); private static final String FilePath = "D:\\"; private static final long serialVersionUID = -8694640030455344419L; public String execute() { //生成的ZIP文件名為Demo.zip String tmpFileName = "Demo.zip"; byte[] buffer = new byte[1024]; String strZipPath = FilePath + tmpFileName; try { ZipOutputStream out = new ZipOutputStream(new FileOutputStream( strZipPath)); // 需要同時下載的兩個文件result.txt ,source.txt File[] file1 = { new File(FilePath+"test1.txt"), new File(FilePath+"測試2.docx") }; for (int i = 0; i < file1.length; i++) { FileInputStream fis = new FileInputStream(file1[i]); out.putNextEntry(new ZipEntry(file1[i].getName())); //設置壓縮文件內的字符編碼,不然會變成亂碼 out.setEncoding("GBK"); int len; // 讀入需要下載的文件的內容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.closeEntry(); fis.close(); } out.close(); this.downFile(getResponse(), tmpFileName); } catch (Exception e) { Log.error("文件下載出錯", e); } return null; } /** * 獲取Response * @return */ private HttpServletResponse getResponse() { return ServletActionContext.getResponse(); } /** * 文件下載 * @param response * @param str */ private void downFile(HttpServletResponse response, String str) { try { String path = FilePath + str; File file = new File(path); if (file.exists()) { InputStream ins = new FileInputStream(path); BufferedInputStream bins = new BufferedInputStream(ins);// 放到緩沖流里面 OutputStream outs = response.getOutputStream();// 獲取文件輸出IO流 BufferedOutputStream bouts = new BufferedOutputStream(outs); response.setContentType("application/x-download");// 設置response內容的類型 response.setHeader( "Content-disposition", "attachment;filename=" + URLEncoder.encode(str, "UTF-8"));// 設置頭部信息 int bytesRead = 0; byte[] buffer = new byte[8192]; // 開始向網絡傳輸文件流 while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) { bouts.write(buffer, 0, bytesRead); } bouts.flush();// 這里一定要調用flush()方法 ins.close(); bins.close(); outs.close(); bouts.close(); } else { response.sendRedirect("../error.jsp"); } } catch (IOException e) { Log.error("文件下載出錯", e); } } }
經過在windows環境下測試通過,使用struts2
- ant-1.6.5.jar (1009.8 KB)