download.java里面的代码,获取服务端存放文件的真实路径之后,把这个文件先写到缓冲区,再把缓冲区的东西写到respond输出流供用户下载。
import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; @WebServlet(name = "download", urlPatterns = { "/download" }) public class download extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = this.getServletContext().getRealPath("/");// 获取真实路径 String downloadFilename = "中文是没有问题的.jpg";// 在下载框默认显示的文件名 downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8"); // 对默认下载的文件名编码。不编码的结果就是,在客户端下载时文件名乱码 File file = new File(filePath + File.separator + "Chrysanthemum.jpg"); if (file.exists()) { // 写明要下载的文件的大小 response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名 response.setContentType("application/octet-stream");// 指明response的返回对象是文件流 // 读出文件到response // 这里是先需要把要把文件内容先读到缓冲区 // 再把缓冲区的内容写到response的输出流供用户下载 FileInputStream fileInputStream = new FileInputStream(file); BufferedInputStream bufferedInputStream = new BufferedInputStream( fileInputStream); byte[] b = new byte[bufferedInputStream.available()]; bufferedInputStream.read(b); OutputStream outputStream = response.getOutputStream(); outputStream.write(b); // 人走带门 bufferedInputStream.close(); outputStream.flush(); outputStream.close(); } } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/10591.html