需求:移动端点击图片触发上传图片或文件或拍照上传。
文件上传

1
2
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。

1
2
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();
}
},
1
2
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"); //触发上传事件
},
1
2
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;
//获取当前token
let token = "Bearer " + window.localStorage.getItem("access_token");
let myHeaders = { Authorization: token };
//更新文件取消上传的source
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”来触发移动端拍照上传。

1
2
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>