JavaWeb实现文件的下载
代码编写:
package com.rong.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
//文件下载
public class FileDown extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载文件的路径
String path = "D://Projects//IdeaProjects//javaweb-01-servlet//response//target//classes//Sea.jpg";
//2.获取下载的文件名
String filename = path.substring(path.lastIndexOf("//") + 1);
//3.让浏览器能够支持下载文件,中文名有可能出现乱码(所以要将文件名转为UTF-8格式)
resp.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(filename,"UTF-8"));
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(path);
//5.创建buffer缓冲区
int len =0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将FileOutputStream写入缓冲区,使用OutputStream将缓冲区的内容写到客户端!
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}