根据一个文件的路径,同时截取这个下载文件的文件名,把他从服务器上下载下来。
package com.fedex.servlet;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class downServlet extends HttpServlet {
private static final long serialVersionUID = -4982148846155613840L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filePath = request.getParameter("filePath");//获得下载文件的路径
String fileName=filePath.substring(filePath.lastIndexOf("\\")+1);//下载后设置的文件名
if(null != filePath){
File downloadFile = new File(filePath);
if(downloadFile.exists()){
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
Long length = downloadFile.length();
response.setContentLength(length.intValue());
ServletOutputStream out = response.getOutputStream();
FileInputStream is = new FileInputStream(downloadFile);
BufferedInputStream bis = new BufferedInputStream(is);
int size = 0;
byte[] b = new byte[4096];
while((size = bis.read(b)) != -1){
out.write(b, 0, size);
}
bis.close();
out.flush();
out.close();
}else{
System.out.println("文件不存在!");
}
}
}
}