之前在项目中遇到图片上传的问题, 其中还是有很多细节要注意.
下面是当时要完成的效果图:
思路: logo1 和 logo2 是同一行, 点击添加又可以添加一行, 这个时候用一个对象数组来存储 logo1 的 name 和 url 属性, 用另外一个对象数组来存储 logo2 的 name 和 url 属性. 同时, 我们点击 "点击上传" 的时候, 要获取到当前的 index, 这样我才知道, 它是给数组中的哪一个进行上传图片.
具体代码:
点击上传
只能上传 jpg/png 文件, 且不超过 3M
点击上传
只能上传 jpg/png 文件, 且不超过 3M
- // 上传前验证
- beforeUpload(file) {
- // 上传支持格式 (.doc/.docx/.pdf/.rar/.zip/.xls/.xlsx/.ppt)
- let reg = /\.(jpg|jpeg|png)$/i;
- if (!reg.test(file.name)) {
- this.$message({
- showClose: true,
- message: '上传支持格式 (.jpg/.jpeg/.png)',
- type: 'error'
- });
- return false;
- }
- else if (file.size> 500 * 1024) {
- this.$message({
- showClose: true,
- message: '文件大小上限为 500K',
- type: 'error'
- });
- return false;
- }
- },
- // 点击上传图
- uploadPic (index) {
- this.index = index;
- },
- // 这个是对于 logo1 上传成功的钩子函数, 因此 logo2 上传成功之后的钩子函数与这个同理
- upLoadSuccess(response, file, fileList) {
- console.log(fileList)
- let self = this;
- if (response.code === 0) {
- if(this.upLoadImg){
- this.$message({
- showClose: true,
- message: '上传成功!',
- type: 'success'
- });
- }
- this.upLoadImg = {
- name: response.data.fileName,
- url: response.data.fileUrl
- }
- this.$set(self.picture, self.index, self.upLoadImg)
- let fileListIndex = fileList.length-1;
- this.benefitList[this.index].logo1 = fileList[fileListIndex].response.data.fileUrl;
- } else {
- // 上传失败清空上传列表
- this.$message({
- showClose: true,
- message: response.msg,
- type: 'error'
- });
- }
- },
来源: https://www.2cto.com/kf/201809/777164.html