javaweb简单的实现文件下载

@RequestMapping(value = "download")
public void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");

//解决乱码问题
String path = new String(request.getParameter("filepath").getBytes("ISO8859-1"),"utf-8");

String filePath = "";
String fileName = "";
if(path != null){
String file[] = path.split("\\\\");
for(int i=0;i<file.length;i++){
if(i==file.length-1){
fileName = file[i];
}else{
filePath += file[i]+"\\";
}
}
}

try {
// 打开文件
// 获取到要下载文件的全路径
// 得到要下载的文件名,小伙伴可以根据自己的实际文件名更改,这里是博主自己定义的文件名
String destinationfileName = new String(fileName);

// 得到要下载的文件的所在目录,同上,小伙伴可以根据自己项目更改内容
String uploadpath = filePath;

// 得到要下载的文件
File file = new File(uploadpath + "\\" + destinationfileName);

//如果文件不存在,则显示下载失败
if (!file.exists()) {
request.setAttribute("message", "下载失败");
request.getRequestDispatcher("/WEB-INF/UploadPSucceed.jsp").forward(request, response);
return;
} else {

// 设置相应头,控制浏览器下载该文件,这里就是会出现当你点击下载后,出现的下载地址框
response.setHeader("content-disposition",
"attachment;filename=" + URLEncoder.encode(destinationfileName, "utf-8"));
// 读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(uploadpath + "\\" + destinationfileName);
// 创建输出流
OutputStream out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[5120];
int len = 0;
// 循环将输入流中的内容读取到缓冲区中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件流
in.close();
// 关闭输出流
out.close();
}
} catch (Exception e) {
// TODO: handle exception

}

}

猜你喜欢

转载自www.cnblogs.com/zhouheblog/p/9632687.html