通用文件强制下载
后端:
@ApiOperation(
value = "通用文件下载",
notes = "通用文件下载"
)
@GetMapping({"/view/{id}"})
public void viewImage(HttpServletResponse response, @PathVariable String id) {
if (Str.isNotEmpty(id)) {
SysFile sysFile = (SysFile)this.sysFileService.getById(id);
if (sysFile != null && Str.isNotEmpty(sysFile.getPath())) {
String filePath = this.uploadPath + sysFile.getPath();
this.outputImage(response, filePath, sysFile.getOriginalName());
}
}
}
private void outputImage(HttpServletResponse response, String filePath, String fileName) {
InputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
File file = new File(filePath);
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment;fileName=" + new String((Str.isNotEmpty(fileName) ? fileName : file.getName()).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
inputStream = new BufferedInputStream(new FileInputStream(filePath));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException var21) {
log.error("预览文件失败" + var21.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException var20) {
log.error(var20.getMessage(), var20);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException var19) {
log.error(var19.getMessage(), var19);
}
}
}
}
前端:
/**
* 下载文件
* @param {*} url
*/
export function XHRLoadFileTwo(url) {
const token = getToken();
let xhr = new XMLHttpRequest()
if (url.charAt(0) !== "/") {
url = "/" + url;
}
xhr.open('get', process.env.BASE_API + url)
//如果需要请求头中这是token信息可以在这设置
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xhr.setRequestHeader('X-Access-Token', token)
xhr.responseType = 'blob'
xhr.send();
// 此处引入了mock需要这样写,mock改写了XMLHttpRequest
if (window._XMLHttpRequest) {
XHRLoadFileTwo_1(xhr)
} else {
xhr.onreadystatechange = function () {
XHRLoadFileTwo_1(xhr)
}
}
}
export function XHRLoadFileTwo_1(xhr) {
if (xhr.readyState === 4 && xhr.status === 200) {
const blob = xhr.response;
const filename = getFilename(xhr.getResponseHeader('content-disposition'));
// 创建一个a标签元素,设置下载属性,点击下载,最后移除该元素
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// 下载
link.click();
// 移除a标签元素
document.body.removeChild(link);
}
}
export function getFilename(header) {
const match = header.match(/fileName=(.*?)(;|$)/);
if (match && match.length > 1) {
return match[1];
} else {
return 'download';
}
}