vue 上传,下载,预览文件及预览TXT时乱码处理

1.上传文件

/*这里顺便写一下再vue中获取input里选择的文件,具体的input属性可去官网查看*/
<input class="import-input" 
	type="file" 
	accept=".xls, .xlsx" 
	ref="importInput" 
	@change="fileChange(e)"/>
	
/*这里只写methods里的方法*/
fileChange (e) {
	// 如果需要验证逻辑,自行添加,比如只支持txt后缀名的文件,e.target等于this.$refs.importInput
	// e.target.files[0].name.split('.')[0];这是文件名
	// e.target.files[0].name.split('.')[1];这是文件后缀名
	this.importFile = e.target.files[0]
	// this.$refs.importInput.files[0]; 这种方式也是可以的
	// e.target.value = '' 或 this.$refs.importInput.value = '';清空input里的值
},
importFile () {
	let file = new FormData();
	file.append('file', this.importFile);
	this.$api.Knowledge.importExcel(file).then(res => console.log(res))
}

/*这里需要对这个请求的请求头header进行设置,在封装axios的时候加上就行*/
axios.post(url,params,{headers:
{'Content-type':'multipart/form-data; boundary=----WebKitFormBoundaryUNNKb1jqWWPagAZR'}})

2.下载文件

参考地址:https://blog.csdn.net/HockJerry/article/details/113128464

3.预览文件

/*
*url请求路径,id参数,name文件名,fileType预览文件的类型
*/
export function downLoad(url,id,name,fileType){
    const req = new XMLHttpRequest();
    const type = fileType
    Loading.open(); // 这是加载中的组件
    req.open('POST', axios.defaults.baseURL+'/'+url, true);
    req.responseType = 'blob';
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      Loading.remove();
      // 这里因为没有对返回的数据处理编码格式,所以在预览txt时需要转换成utf-8
      const data = type == 'txt' ? new Blob([req.response], {type: 'application/json;charset=utf-8'}) : req.response;
      const datas = window.URL.createObjectURL(req.response)
      let blobUrl = window.URL.createObjectURL(data);
      localStorage.setItem('pdfName', name);
      window.open(blobUrl,'PDF','width:50%;height:50%;top:100;left:100;');
    };
    req.send(id);
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值