@WebServlet("/download")
public class DowenloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileName= req.getParameter("file");
String name = req.getParameter("name");
System.out.println(fileName);
File saveDir = new File("D:/upload");
File file = new File(saveDir,fileName);
if(file.exists()){
if(StringUtils.isNotEmpty(name)){
//设置文件头 二进制文件代码为了让浏览器不识别 而弹窗
resp.setContentType("application/octet-stream");
//告诉浏览器下载文件大小,浏览器知道大小会在下载进度条上有区别
//resp.setContentLengthLong(file.length());
resp.setContentLength((int) file.length());
//下载文件名为中文出现乱码 如下解决
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
//设置下载的文件名
resp.addHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");
}
//响应输出流
OutputStream outputStream = resp.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
IOUtils.copy(fileInputStream,outputStream);
outputStream.flush();
outputStream.close();
fileInputStream.close();
}else {
resp.sendError(404,"文件未找到");
}
}
}
网友评论