@RequestMapping("/download")
public String download(String uploadpath, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// uploadpath是指欲下载的文件的路径。例如绝对路径是 /home/workspace/1.txt
File file = new File(uploadpath);
//获取文件名称,截取字符串,根据最后一个/截取,可取文件名称
int endlength=uploadpath.lastIndexOf("/");
String filename=uploadpath.substring(endlength+1, uploadpath.length());
System.out.println("文件名称是:"+filename);
// 取得文件的后缀名。
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
long fileLength = new File(uploadpath).length();
response.setContentType("application/x-msdownload;"); //设置下载的格式
response.setHeader("Content-Length", String.valueOf(fileLength));
//用来解决下载的文件名称乱码的问题,ISO8859-1格式可以避免下载文件名称字数限制的问题
response.setHeader("Content-disposition",
"attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
//读取文件
bis = new BufferedInputStream(new FileInputStream(uploadpath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
//写入文件
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
public String download(String uploadpath, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// uploadpath是指欲下载的文件的路径。例如绝对路径是 /home/workspace/1.txt
File file = new File(uploadpath);
//获取文件名称,截取字符串,根据最后一个/截取,可取文件名称
int endlength=uploadpath.lastIndexOf("/");
String filename=uploadpath.substring(endlength+1, uploadpath.length());
System.out.println("文件名称是:"+filename);
// 取得文件的后缀名。
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
long fileLength = new File(uploadpath).length();
response.setContentType("application/x-msdownload;"); //设置下载的格式
response.setHeader("Content-Length", String.valueOf(fileLength));
//用来解决下载的文件名称乱码的问题,ISO8859-1格式可以避免下载文件名称字数限制的问题
response.setHeader("Content-disposition",
"attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
//读取文件
bis = new BufferedInputStream(new FileInputStream(uploadpath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
//写入文件
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}