捣鼓了捣鼓了下载文件,虽然具体的响应头的知识和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();
}
}
原文地址:https://www.cnblogs.com/woshi123/p/12557994.html
时间: 2024-10-10 23:24:12