JavaWeb使用response下载文件

最主要的就是写doGet方法了,先上代码。

package com.harris.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class ServletDown extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取文件下载的路径,这里的路径一定要写对.
        String realPath = "D:\\Java_Project\\JavaWeb\\Servlet-down\\target\\classes\\1.jpg";
        System.out.println("文件的路径为:"+realPath);
        //2.获取文件名,便于后面的写response的Header信息.
        String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
        //3.设置响应头信息的Content-Disposition (内容设置)属性
        //attachment 表示类型是附件 后面是文件名
        resp.setHeader("Content-Disposition","attachment;filename="+filename);
        //4.文件用字节数组读取文件字节流,然后输出字符流.
        FileInputStream fi = new FileInputStream(realPath);
        int len=0;
        byte[] buffer = new byte[1024];
        ServletOutputStream out = resp.getOutputStream();
        while((len=fi.read(buffer))>0){
            out.write(buffer,0,len);
        }
        fi.close();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}


关于Content-Disposition 的介绍:

传送门

一个小问题,转到 / d o w n /down /down 界面后提出 r e s q u e s t resquest resquest后会自动下载,而不会弹出提示框是否保存,待解决。