需求:移动端点击图片触发上传图片或文件或拍照上传。
文件上传
| 12
 3
 4
 
 | <a><input type="file" ref="file" hidden @change="onInputChange('file')" />
 <img src="@/assets/images/uploading-link.png" @click="triggerUpload('file')" />
 </a>
 
 | 
首先设置hidden属性隐藏一个input,input的type属性设置为文件,通过img标签的@click事件触发input。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | triggerUpload(type) {
 let _this = this;
 if (this.fileList.length >= this.limit) {
 alert("文件上传数量超出限制");
 return false;
 } else {
 this.$refs.file.click();
 }
 },
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | 
 onInputChange(item) {
 let _this = this;
 if (item == "file") {
 let file = this.$refs.file.files[0];
 if (file.size > this.size) {
 alert("文件太大无法上传");
 return false;
 }
 _this.fileUpload(file, "file");
 },
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 
 | fileUpload(file, type) {
 let _this = this;
 let form = new FormData();
 let url = _this.url;
 
 let token = "Bearer " + window.localStorage.getItem("access_token");
 let myHeaders = { Authorization: token };
 
 source = CancelToken.source();
 form.append("file", file);
 Axios.post("/文件上传接口", form, {
 cancelToken: source.token,
 headers: myHeaders,
 })
 .then((res) => {
 _this.onSuccessDefault(res, file, type);
 })
 .catch(function (error) {
 if (Axios.isCancel(error)) {
 console.log("Request canceled", error.message);
 }
 _this.onErrorDefault(error);
 });
 },
 
 onSuccessDefault(res, file, type) {
 var _this = this;
 console.log("file:", file);
 if (res.data.code == "000000") {
 _this.$Message.success("上传成功!");
 var fileInfo = {
 fileName: res.data.resultBody.fileName,
 opTime: res.data.resultBody.optime,
 filePath: res.data.resultBody.ftpUrl,
 fileSize: (file.size/1024).toFixed(2)+"KB",
 };
 _this.fileList.push(fileInfo);
 } else {
 };
 },
 
 onErrorDefault(error) {
 console.log("error", error);
 this.$Message.error("上传失败");
 },
 
 | 
最后将fileList和表单一起提交。
图片上传和拍照上传
过程与文件上传相同,图片上传设置 accept=”image/“,拍照上传设置 accept=”image/“ 外,设置 capture=”camera”来触发移动端拍照上传。
| 12
 3
 4
 5
 6
 7
 8
 
 | <a><input type="file" ref="photo" hidden @change="onInputChange('photo')" accept="image/*" />
 <img src="@/assets/images/uploading-img.png" @click="triggerUpload('photo')" />
 </a>
 <a>
 <input  type="file" accept="image/*"  hidden capture="camera" @change="onInputChange('cameraPhoto')" ref="cameraPhoto"  />
 <img src="@/assets/images/uploading-photo.png" @click="triggerUpload('cameraPhoto')" />
 </a>
 
 |