问题遇到的现象和发生背景
视频和图片下载出现问题
问题相关代码,请勿粘贴截图
package cn.itcast.web.download;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
@WebServlet("/downloadServlet")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1获取请求参数,文件名称
String filename = req.getParameter("filename");
// 2使用字节输入流将文件加载到内存
// 2.1找到文件服务器路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
// 2.2用字节输入流
FileInputStream fis=new FileInputStream(realPath);
// 3设置response的响应头操作 content-type
String mimeType = servletContext.getMimeType(filename);//获取mime的类型
resp.setHeader("content-type",mimeType);
// 设置另一个响应头 context-disposition
resp.setHeader("Content-Disposition","attachment;filename="+filename);
// 4将输入流数据写到输出流数据
ServletOutputStream sos=resp.getOutputStream();
byte[] buff=new byte[1024 * 8];
int len=0;
while ((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
fis.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="/day14/img/1.jpg" download>图片</a>
<a href="/day14/img/Eclipse.mp4" download>图片</a>
<hr>
<a href="/day14/downloadServlet?filename=1.jpg" download>图片</a>
<a href="/day14/downloadServlet?filename=Eclipse.mp4" download>视频</a>
</body>
</html>
运行结果及报错内容
不能够下载 以及报错500
我的解答思路和尝试过的方法
修改路径和debug
我想要达到的结果
能够下载视频和图片