后台:
/**
* 下载文件
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/download")
public ResponseEntity<byte[]> downloadFile(HttpServletRequest request) throws IOException {
if(request.getParameter("filePath") == "")
return new ResponseEntity<byte[]>(null, null, HttpStatus.NO_CONTENT);
String filePath = request.getParameter("filePath");
File file = new File(filePath);
HttpHeaders headers = new HttpHeaders();
String fileName =filePath.substring(filePath.lastIndexOf("/")+1) ;
String fileName2 = new String(fileName.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName2);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
前台:
//文件下载
function downloadFile(filePath){
window.location.href = './downloadHandbook?filePath='+filePath;
}
<a href="#" class="col_g" onClick="downloadFile('${row.hbUrl}')">下载</a>