使用Vue时,我们前端如何处理后端返回的文件流
首先后端返回流,这里我把流的动作拿出来了,我很多地方要用
/**
* 下载单个文件
*
* @param docId
*/
@GetMapping("/download/{docId}")
public void download(@PathVariable("docId") String docId,
HttpServletResponse response) {
outWrite(response, docId);
}
/**
* 输出文件流
* @param response
* @param docId
*/
private void outWrite(HttpServletResponse response, String docId) {
ServletOutputStream out = null;
try {
out = response.getOutputStream();
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
byte[] bytes = docService.downloadFileSingle(docId);
if (bytes != null) {
MagicMatch match = Magic.getMagicMatch(bytes);
String mimeType = match.getMimeType();
response.setContentType(mimeType);
out.write(bytes);
}
out.flush();
} catch (Exception e) {
UnitedLogger.error(e);
} finally {
IOUtils.closeQuietly(out);
}
}
前端这里我引入了一个组件 js-file-download
npm install js-file-download --save
然后在Vue文件中添加进来
import fileDownload from "js-file-download";
// 文档操作列对应事件
async handleCommand(item, data) {
switch (item.key) {
case "download":
var res = await this.download(data);
return fileDownload(res, data.name);
...
default:
}
// 刷新当前层级的列表
const folder = this.getLastFolderPath();
this.listClick(folder.folderId, folder.name);
},
// 下载
async download(row) {
if (this.isFolder(row.type)) {
return FolderAPI.download(row.id);
} else {
return DocAPI.download(row.id);
}
},
docAPI js 注意需要设置responseType
/**
* 下载单个文件
* @param {*} id
*/
const download = (id) => {
return request({
url: _DataAPI.download + id,
method: "GET",
responseType: 'blob'
});
};
这样即可成功下载。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)