文件下载

代码实现:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 下载图片
 * @author Administrator
 *
 */
public class TestDownLoad extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取需要下载文件的名字
        String fileName = req.getParameter("fileName");
        //转换编码
        byte[] bytes = fileName.getBytes("ISO-8859-1");
        fileName = new String(bytes,"UTF-8");

        //通知浏览器以下载的方式打开文件,如果下载框中显示的文字是中文的话,又要编码,浏览器弹出的下载框来解码
        resp.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));

        //假设用户选中“保存”,/表示web项目
        InputStream is = this.getServletContext().getResourceAsStream("/images/上海地铁图.gif");
        OutputStream os = resp.getOutputStream();

        byte[] buf = new byte[1024*4];
        int len = 0;
        while ((len=is.read(buf))!=-1) {
            os.write(buf,0,len);
        }

        is.close();
        os.close();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

jps页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片下载</title>
</head>
  <body>
    <!-- /表示webapps目录
         对于GET请求后边带中文的情况下,需要进行UTF-8编码后,再传递到服务器
     -->
    <a href="/javaweb/demo11?fileName=%E4%B8%8A%E6%B5%B7%E5%9C%B0%E9%93%81%E5%9B%BE.gif" style="text-decoration:none;">上海地铁图.gif</a>
  </body>
</html>
原文地址:https://www.cnblogs.com/Darkqueen/p/9047794.html