Vue2下载二进制文件
后端:
controller:
@GetMapping(value = "/get-import-template")
public void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
iUserService.problemTemplate(request, response);
}
service:
void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception;
impl:
@Override
public void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
String path = "file/user.xlsx";
// 从类加载器获取资源
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("产品运输阶段导入模版.xlsx", "UTF-8"));
// 获取ServletOutputStream
ServletOutputStream outputStream = response.getOutputStream();
// 使用Apache POI的XSSFWorkbook将Excel文件写入输出流
try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {
workbook.write(outputStream);
} finally {
// 确保输出流被关闭
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
}
}
前端:
html:
//批量导入
<el-dialog :title="title" :visible.sync="importFormVisible" width="800px" :close-on-click-modal="false" :show-close="false">
<div class="tip">
<div class="bold">1</div>
<span class="btitle">下载模版</span>
</div>
<el-row :gutter="24">
<div class="el-upload__tip text-center">
<span>仅允许导入 xls、xlsx 格式文件;请按照要求填写模版文件</span>
<el-link
:underline="false"
style="font-size: 12px; vertical-align: baseline"
type="primary"
@click="importTemplate"
>
下载导入模板
</el-link>
</div>
</el-row>
<div style="padding: 8px 0; background: #f8fbff; margin-top: 10px">
<div class="tip">
<div class="bold">2</div>
<span class="btitle">导入文件</span>
</div>
</div>
<div style="padding: 8px 0; background: #f8fbff; margin-top: 10px">
<div class="tip">
<div class="bold">3</div>
<span class="btitle">删除</span>
</div>
<el-row :gutter="24">
<el-input
v-model="importBatch"
placeholder="请输入批次号"
clearable
class="!w-240px"
/>
<el-button @click="handleDelete">按批次号删除导入数据</el-button>
</el-row>
</div>
<div style="text-align:center;">
<el-button type="primary" @click="saveUser">确定</el-button>
<el-button type="danger" @click="importFormVisible = false">取消</el-button>
</div>
</el-dialog>
js:
//下载导入模板
importTemplate(){
importTemplate().then((res) => {
console.log(res, 'res')
const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
// 创建 href 超链接,点击进行下载
window.URL = window.URL || window.webkitURL
const href = URL.createObjectURL(blob)
const downA = document.createElement('a')
downA.href = href
downA.download = '组织架构用户导入模板.xlsx'
downA.click()
// 销毁超连接
window.URL.revokeObjectURL(href)
});
},
实现效果: