[AppleScript] 纯文本查看 复制代码
@WebServlet("/downloadPictures")
public class downloadPictures extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.根据参数获取请求的文件名
String filename = request.getParameter("filename");
//2.根据文件名获取真实路径
ServletContext servletContext = this.getServletContext();
String realPath = servletContext.getRealPath("/img/" + filename);
//3.创建字节流并关联文件
FileInputStream fis = new FileInputStream(realPath);
System.out.println(realPath);
//设置响应数据格式,设置打开方式:附件,不写下面这一段则会以图片形式显示在网页上
//4.设置响应头,本次响应数据的格式的MIME格式,有些浏览器不添加这个响应头也可以解析出来,但大部分还是要加上的
String mimeType = servletContext.getMimeType(filename);//获取文件的mime类型
response.setHeader("content-type",mimeType);
//转换为浏览器的编码的名字(解决文件名乱码问题)
String agent = request.getHeader("user-agent");
filename = DownLoadUtils.getFileName(agent, filename);
response.setHeader("content-disposition","attachment;filename="+filename); //注意:attachment后面是分号,不是逗号!
PrintWriter writer = response.getWriter(); //此处出现错误:和字节流冲突,不可同时使用,只获取不使用也不行
ServletOutputStream sos = response.getOutputStream();
byte[] buff = new byte[1024*8];
int len = 0;
while ((len=fis.read(buff))!=-1){
sos.write(buff,0,len);
}
sos.close();
fis.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response); //这里一定不要忘记!
}
}