java后端解析文件返回文件流,前端自定义文件名

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()
				})
			},
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值