利用response和HttP中的Content-Disposition: attachment; filename=aaa.zip响应头,实现简单的文件下载

中文名称的文件下载需要注意的问题:

  1、在设置response响应为Content-Disposition: attachment; filename=aaa.zip,通知浏览器以下载的方式处理服务器发来的数据。

  2、对于中文名称的文件,需要利用URLEncoder.encode(filename,"utf-8"),对中文进行编码,即可

完整的文件下载程序如下package com.baowei.servletimport java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;

import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.baowei.persondao.PersonDao; public class FristServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { fileDownload(resp); } private void fileDownload(HttpServletResponse resp) throws IOException { ServletContext context = this.getServletContext(); String realpath = context.getRealPath("/哈哈.png"); String filename = realpath.substring(realpath.lastIndexOf("\\") + 1); System.out.println(filename);
// resp.setContentType("image/png"); ,用于图片的显示
 //中文的文件名需要进行URLEncoder.encode(filename,"utf-8")的处理 resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8")); FileInputStream is = new FileInputStream(realpath); byte[] buffer = new byte[1024]; int len = 0;
OutputStream out
= resp.getOutputStream(); while ((len = is.read(buffer)) != -1) { out.write(buffer, 0, len); } out.flush(); is.close(); } }

 

你可能感兴趣的:(利用response和HttP中的Content-Disposition: attachment; filename=aaa.zip响应头,实现简单的文件下载)