废话不多说,上代码
1 package com.mlq.servlet; 2 3 import com.sun.net.httpserver.HttpsServer; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.ServletOutputStream; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import java.io.FileInputStream; 11 import java.io.IOException; 12 import java.net.URLEncoder; 13 14 public class ServletReponseDFile extends HttpServlet { 15 @Override 16 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 17 // § 获取现在文件的路径 18 // § 下载的文件名 19 // § 设置让浏览器支持我们需要的下载的东西,让URLEncoder.encode编码,否则可能乱码 20 // § 获取下载文件的输入流 21 // § 创建缓冲区 22 // § 获取OutputStream对象 23 // § =将FileOutputStream流写入到buffer缓冲区 24 // 使用OutputStream,将缓冲区中的数据输出到客户端中 25 String realPath="D:/Javacode/servletWebappDemo2/servletWebappDemo2/src/main/resources/1.jpg"; 26 String filename=realPath.substring(realPath.lastIndexOf("/")+1); 27 resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename,"utf-8")); 28 FileInputStream in=new FileInputStream(realPath); 29 byte[] bytes=new byte[1024]; 30 int len=0; 31 ServletOutputStream out = resp.getOutputStream(); 32 while ((len=in.read(bytes))>0){ 33 out.write(bytes,0,len); 34 } 35 } 36 37 @Override 38 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 39 doPost(req, resp); 40 } 41 }
标签:文件,realPath,resp,IOException,import,servlet,javax,下载 From: https://www.cnblogs.com/Mexcellent/p/17382777.html