下载、上传、预览功能实现总结

1.在小程序上的实现
(1)小程序的上传不支持上传整个文件对象(可以看微信小程序开发文档进行了解),上传文件:

// 上传
			upload(){
     
				// let that = this;
				wx.chooseMessageFile({
     
				  count: 1,
				  type: 'file',
				  success : (res) => {
     
				    // tempFilePath可以作为img标签的src属性显示图片
				    const tempFilePaths = res.tempFiles
					console.log(tempFilePaths);
					uni.uploadFile({
     
					    url: this.$service+'/user/uploadResumeFile.do', 
					    filePath: tempFilePaths[0].path,
					    name: 'file',
						// header: {
     
						// 	"Content-Type": "multipart/form-data"
						// }, 
					     formData: {
     
					         'resumeid': this.userDetail.uid,
							  'fileName' : tempFilePaths[0].name		
					     },
					    success: (uploadFileRes) => {
     
							uni.showToast({
     
								title: JSON.parse(uploadFileRes.data).msg,
								icon: 'none',
								duration: 2000
							})
							this.userDetail.filename = JSON.parse(uploadFileRes.data).filename;
							this.userDetail.filepath = JSON.parse(uploadFileRes.data).fileurl;
					        console.log(JSON.parse(uploadFileRes.data));
							
					    },
						fail:(uploadFileRes)=>{
     
						    uni.showToast({
       
						        title: '请求错误',  
						        duration: 2000  
						    }); 
						} 
					});
				  }
				});
			}	

(2)小程序文件的下载一般会保存在微信的文件路径里面,一般不容易找到,我们可以利用第三方软件打开进行保存。文件的下载和预览:

	// 下载
			downLoad(filePath) {
     
				 uni.downloadFile({
     
				 	 url: this.$service +'/' + filePath,
				 	success: (res) => {
     
						uni.openDocument({
     
							filePath: res.tempFilePath,
							success: (res) => {
     	
								uni.showToast({
     
									title: '成功打开文档',
									icon: 'none',
									duration: 2000
								})
								// console.log('成功打开文档')
								// console.log('openDocumentres', res)
							},
							fail: (err) => {
     
								console.log('openDocumenterr', err)
							}
						})
					 },
					 fail: (err) => {
     
					 console.log('downloadFile fail, err is:', err)
					 	uni.showModal({
     
					 		title: '下载失败',
					 		content: '失败原因: ' + JSON.stringify(err),
					 		showCancel: false
					 	});
					 }
				 })
			},

2.pc端文件的下载、保存、预览,一般利用标签的href属性:
(1)文件的下载:
当下载时需要传递多个参数时,选择这种方式下载:
要注意在使用这种方法下载时,要设置:

		headers: {
     
		      "Content-Type": "application/json;application/octet-stream"
		},
		responseType: "blob",

exportStudent() {
     
				let form = {
     
					operatorid: this.pageRequest.operatorid,
					college: this.formInline.college,
					major: this.formInline.major,
					education: this.formInline.education,
					graduateyear: this.formInline.graduateyear,
					studentname: this.formInline.studentname,
					studentnum: this.formInline.studentnum,
					recordtype: this.formInline.recordtype
				}
				this.$api.appFair.exportStudent(form).then(res => {
     
					const content = res.data;
					const blob = new Blob([content]);
					var date = new Date().getFullYear() + "" + (new Date().getMonth() + 1) + "" + new Date().getDate();
					const fileName = date + name + ".xlsx";
					if ("download" in document.createElement("a")) {
     
						// 非IE下载
						const elink = document.createElement("a");
						elink.download = fileName;
						elink.style.display = "none";
						elink.href = URL.createObjectURL(blob);
						document.body.appendChild(elink);
						elink.click();
						URL.revokeObjectURL(elink.href); // 释放URL 对象
						document.body.removeChild(elink);
					} else {
     
						// IE10+下载
						navigator.msSaveBlob(blob, fileName);
					}
				})
			}

当不需要传递参数下载时,有文件的下载地址,可以直接使用标签:

<a :href="imgUrl+'/userStudent/downTemplateExcel.do'">点击下载</a>

(2)文件的上传:
使用elementui的上传组件进行上传:

//其中设置auto-upload="false"可以取消自动上传行为,我用于设置提交表单时触发上传事件,不需要设置提交表单触发上传事件的,可以不用设置,data属性中的myData是我设置上传的参数对象
<el-upload class="upload-demo" :action="imgUrl+'/userStudent/importExcel.do'" :data="myData" :limit="1" accept=".xls,.xlsx"
									 :on-success="uploadSuccess" name="userExcel" :auto-upload="false"  ref="upload">
										<el-button size="small" type="primary">选择文件</el-button>
</el-upload>
//表单提交触发上传事件
submitForm(){
     
this.$refs[form].validate(async valid => {
     
					if (valid) {
     
						this.$refs.upload.submit();  //提交上传
					} else {
     
						return false;
					}
				});
}

不需要设置表单提交触发上传的:

<el-upload ref="upload" :action="imgUrl+'/user/uploadResumeFile.do'" :data="uploadData" :on-success="uploadFileSuccess"
							 :limit="1" :before-upload="beforeUpload" :show-file-list="false">
								上传
</el-upload>

// 上传之前
			beforeUpload(file) {
     
				this.uploadData.fileName = file.name;
				this.uploadData.resumeid = this.user.uid;
				console.log(file);
			},
			// 上传成功
			uploadFileSuccess(res) {
     
				this.user.filename = res.filename;
				this.user.fileurl = res.fileurl;
				this.$refs.upload.clearFiles();
				this.$message(res.msg);
			}
(3)文件的预览,可以实现在线预览pdf和doc格式的文件,docx的文件可能会有错误
使用标签和XDOC可以实现预览以DataURI表示的DOC文档
 <a :href="'http://www.xdocin.com/xdoc?_func=to&_format=html&_cache=1&_xdoc='+imgUrl+'/'+user.filepath"
								 target="_blank" rel="nofollow"><img src="../../assets/[email protected]" class="baseIcon" />预览</a>
	实现预览的方法有很多,目前只尝试了这种,网上还有很多种方法供我们体验

你可能感兴趣的:(vue,uni-a)