protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置ContentType字段值 response.setContentType("text/html;charset=utf-8"); //获取所要下载的文件名称 String filename = request.getParameter("filename"); //下载文件所在目录 // 通知浏览器以下载的方式打开 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename="+filename); // 通过文件流读取文件 String path=request.getSession().getServletContext().getRealPath("/file/"+filename); System.out.println(path); InputStream in = new FileInputStream(path); String save="E:/download/" +filename; Path path1= Paths.get(save); Files.copy(in,path1); // 获取response对象的输出流 OutputStream out = response.getOutputStream(); Files.copy(path1,out); out.flush(); // byte[] buffer = new byte[1024]; // int len; // //循环取出流中的数据 // while ((len = in.read(buffer)) != -1) { // out.write(buffer, 0, len); // } // out.close(); // in.close(); }修改代码实现文件下载
时间: 2024-03-07 17:47:02 浏览: 136
基于javaweb上机报告.doc
以下是修改后的代码,实现了文件下载:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置ContentType字段值
response.setContentType("text/html;charset=utf-8");
//获取所要下载的文件名称
String filename = request.getParameter("filename");
//下载文件所在目录
String filePath = request.getServletContext().getRealPath("/file/" + filename);
File downloadFile = new File(filePath);
//判断文件是否存在
if (downloadFile.exists()) {
//设置响应头,告诉浏览器是下载文件
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + filename);
//将文件从服务器读取到内存中,再写入到响应流中
FileInputStream in = new FileInputStream(downloadFile);
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
} else {
//文件不存在,返回404状态码
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
```
这里使用了`doGet`方法,因为文件下载一般是通过GET请求实现的。另外,代码中还做了文件存在性的判断,如果文件不存在,则返回404状态码。
阅读全文