/**
* 下载/浏览器中打开文件
*
* @param id
* @return
* @throws Exception
*/
@ResponseBody
@GetMapping("downloadFile")
@ApiOperation(value = "下载/浏览器中打开", notes = "")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query", dataType = "Long", name = "open", example = "0", value = "是否打开", required = true),
@ApiImplicitParam(paramType = "query", dataType = "Long", name = "id", example = "0",value = "文件id", required = true) })
public void downloadFile(HttpServletResponse response, HttpServletRequest request, Integer open, Long id) throws Exception {
SmUploadFile fileInfo = uploadFileService.getUploadFileById(id);
try {
// path是指欲下载的文件的路径。
File fileOnserver = new File(fileInfo.getFilePath());
// 取得文件名。
String filename = fileInfo.getFileName();
// 取得文件的后缀名。
String ext = null;
if(fileInfo.getFilePath().lastIndexOf(".")>0){
ext = fileInfo.getFilePath().substring(fileInfo.getFilePath().lastIndexOf("."));
}
if(ext!=null && filename.indexOf(ext)<0){
filename = filename + ext;
}
String userAgent = request.getHeader("User-Agent");
if(userAgent.toUpperCase().indexOf("TRIDENT") > 0) {
filename = new String(filename.getBytes("GBK"), "ISO8859-1");
} else if (userAgent.toUpperCase().indexOf("MSIE") > 0) {
filename = URLEncoder.encode(filename, "UTF-8");
} else {
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
}
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(fileOnserver));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Length", "" + fileOnserver.length());
response.addHeader("Access-Control-Allow-Origin", "*");
String contentType = fileInfo.getContentType();
if(open!= null && open == 1 && contentType != null){
response.setContentType(contentType);
} else {
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + filename);
}
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}