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);
}
Logo

前往低代码交流专区

更多推荐