文件下载有一个问题就是如果我们要下载图片,但是浏览器会自动缓存这个图片,也就是说我们可以在浏览器上面直接看到图片,而不是下载下来,所以我们需要更改响应头的content-disposition的类型为attachment,从而让浏览器无法解析这个文件(attachment指的是附件),然后就需要用到response的输出流,通过resq.getOutputStream()获得。还有就是我们的文件是需要放到WebContent里面的(如果是就在WebContent下面,则写“/xxx.jpg”,如果是WebContent下的某个文件,则写 “/文件名/xxx.jpg”),接下来是代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="/javaweb01/download?filename=1.jpg">picture</a>
</body>
</html>
Java的代码:
public class filedownload extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("having been using the get!");
String str=req.getParameter("filename");
resp.setHeader("content-disposition", "attachment");
if(str.equals("1.jpg"));
{
ServletOutputStream fos=resp.getOutputStream();
FileInputStream fi=new FileInputStream("/1.jpg");
byte[] by= new byte[100*1024*1024];
fi.read(by);
fos.write(by);
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}