java后端解析文件返回文件流,前端自定义文件名
请求属性:responseType: ‘blob’
后台代码示例
```java
public static void exportMillCertificateWord(HttpServletRequest request, HttpServletResponse response, Map map,
String fileName, String ftlName) throws IOException {
File file = null;
InputStream fin = null;
ServletOutputStream out = null;
file = createDoc(map, ftlName, fileName);
if (response != null) {
response.reset();
}
if (file.exists()) {
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 文档下载
response.setCharacterEncoding("utf-8");
//response.setContentType("application/x-msdownload");
try {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".doc");
try {
out = response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[512]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中
try {
while ((bytesToRead = fin.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null)
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
if (out != null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
if (file != null)
file.delete(); // 删除临时文件
}
}
}
## 前端代码实例
```javascript
creatWord() {
this.timeStr = this.dateStr(new Date(),'-');
creatWord().then((res) => {
if(!res) {
return;
}
let blob = new Blob([res.data], {
type: "application/msword"
});
let url = window.URL.createObjectURL(blob)
let link = document.createElement('a')
link.download = '申报书打印版'+this.timeStr+'.doc'
link.style.display = 'none'
link.href = url
document.body.appendChild(link)
link.click()
})
},