文件的下载

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

    <servlet>
        <servlet-name>DownloadServlet</servlet-name>
        <servlet-class>com.zr.uploaddownload.servlet.DownloadServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>DownloadServlet</servlet-name>
        <url-pattern>/downloadServlet</url-pattern>
    </servlet-mapping>

</web-app>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
 
    
    <title>test download</title>
   

  </head>
  
  <body>
    
    <a href="downloadServlet">下载</a>

  </body>
</html>
package com.zr.uploaddownload.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class DownloadServlet extends HttpServlet{
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e1) {
            
            e1.printStackTrace();
        }
        
        // 设置
        resp.setContentType("application/x-msdownload");
        try {
            resp.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("我爱罗.jpg","utf-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        //被下载文件的路径
        String sourcePath = "C:\Users\Administrator\Desktop\我爱罗.jpg";
        File file = new File(sourcePath);
        
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        
        try {
            fis = new FileInputStream(file);
            try {
                sos = resp.getOutputStream();
                byte[] b = new byte[1024];
                int i;
                while ((i=fis.read(b))!=-1) {
                    sos.write(b, 0, i);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally{
            if (fis!=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
}
原文地址:https://www.cnblogs.com/lantu1989/p/6258697.html