import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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(urlPatterns = "/fileDownLoad")
public class FileDownLoad extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取域对象
ServletContext servletContext = req.getServletContext();
// 获取请求内的文件名称
String filename = req.getParameter("filename");
// 获取请求文件的绝对路径
String realPath = servletContext.getRealPath("./image/" + filename);
// 获取响应头的MIME类型名称
String mimeType = servletContext.getMimeType(filename);
// 设置响应头的类型为文件所对应的Mime类型
resp.setHeader("content-type", mimeType);
// 设置中文乱码问题
filename = DownLoadUtils.getFileName(req.getHeader("user-agent"),filename);
// 设置与文件对应的MIME类型
resp.setHeader("content-disposition", "attachment;filename=" + filename);
// inputStream 读取到内存
FileInputStream fileInputStream = new FileInputStream(realPath);
// 将获取到的数据先展示到控制台
byte[] temp_arr = new byte[1024 * 8];
// 获取到的每一行的数据的长度
int len = 0;
// 写出数据到页面
while ((len = fileInputStream.read(temp_arr)) != -1) {
/* System.out.println(temp_arr);
System.out.println("Length is : " + len);*/
// 写出数据到页面
resp.getOutputStream().write(temp_arr, 0, len);
}
fileInputStream.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
}
Java>>Servlet,response.getOutputStream().write(byte[], 0, len);文件下载
猜你喜欢
转载自blog.csdn.net/weixin_43309893/article/details/118266935
今日推荐
周排行