码迷,mamicode.com
首页 > 其他好文 > 详细

Response下载文件

时间:2020-03-24 12:54:29      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:protected   indexof   write   context   fileinput   vax   text   string   com   

捣鼓了捣鼓了下载文件,虽然具体的响应头的知识和HttpServletResponse、ServletResponse的有些方法了解的还不够详细。。。。

package com.woshi.servlet;

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

@WebServlet("/download")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String download = getServletContext().getRealPath("WEB-INF/downloads/download.jpg");
        String fileName = download.substring(download.lastIndexOf("\\")+1);
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        FileInputStream inputStream = new FileInputStream(download);
        ServletOutputStream servletOutputStream = resp.getOutputStream();
        byte[] bbuf = new byte[1024];
        int hasRead = 0;
        while ((hasRead=inputStream.read(bbuf))>0){
            servletOutputStream.write(bbuf,0,hasRead);
        }
        inputStream.close();
        servletOutputStream.close();
    }
}

Response下载文件

标签:protected   indexof   write   context   fileinput   vax   text   string   com   

原文地址:https://www.cnblogs.com/woshi123/p/12557994.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!