- 要获取下载文件的路径
- 下载的文件名是啥?
- 设置想办法让浏览器能够支持下载我们需要的东西
- 获取下载文件的输入流
- 创建缓冲区
- 获取OutputStream对象
- 将FileOutputStream流写入到bufer缓冲区
- 使用OutputStream将缓冲区中的数据输出到客户端!
package com.beijing.servlet.File;
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.*;
import java.net.URLEncoder;
public class FileDownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.download(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
private void download(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String relPath = "C:\\Users\\史凯翔\\Pictures\\Camera Roll\\afe7fab630484fefa566d24294c18408.jpg";
String fileName = relPath.substring(relPath.lastIndexOf("\\") + 1);
resp.setHeader("ContentDisposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
FileInputStream fis = new FileInputStream(relPath);
BufferedInputStream bis = new BufferedInputStream(fis);
int len = 0;
byte[] bytes = new byte[1024];
ServletOutputStream os = resp.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
while ((len = bis.read(bytes)) > 0) {
bos.write(bytes,0,len);
}
bis.close();
fis.close();
bos.close();
os.close();
}
}