element-ui upload图片上传组件使用

图片上传前端收集 数据 再调用接口发送到后端

组件标签内的参数:

参数 说明 类型 可选值 默认值
action 必选参数,上传的地址 string
headers 设置上传的请求头部 object
multiple 是否支持多选文件 boolean
data 上传时附带的额外参数 object
name 上传的文件字段名 string file
with-credentials 支持发送 cookie 凭证信息 boolean false
show-file-list 是否显示已上传文件列表 boolean true
drag 是否启用拖拽上传 boolean false
accept 接受上传的文件类型(thumbnail-mode 模式下此参数无效) string
on-preview 点击文件列表中已上传的文件时的钩子 function(file)
on-remove 文件列表移除文件时的钩子 function(file, fileList)
on-success 文件上传成功时的钩子 function(response, file, fileList)
on-error 文件上传失败时的钩子 function(err, file, fileList)
on-progress 文件上传时的钩子 function(event, file, fileList)
on-change 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 function(file, fileList)
before-upload 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。 function(file)
before-remove 删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。 function(file, fileList)
list-type 文件列表的类型 string text/picture/picture-card text
auto-upload 是否在选取文件后立即进行上传 boolean true
file-list 上传的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] array []
http-request 覆盖默认的上传行为,可以自定义上传的实现 function
disabled 是否禁用 boolean false
limit 最大允许上传个数 number
on-exceed 文件超出个数限制时的钩子 function(files, fileList) -

Slot

name 说明
trigger 触发文件选择框的内容
tip 提示说明文字

Methods

方法名 说明 参数
clearFiles 清空已上传的文件列表(该方法不支持在 before-upload 中调用)
abort 取消上传请求 ( file: fileList 中的 file 对象 )
submit 手动上传文件列表

 组件的模板结构:

          <el-upload 
            ref="upload" 打标识上 upload
            class="upload-demo"  样式类名
            :action="actionToUrl" 默认上传的地址
            :on-preview="handlePreview2" 预览已上传图片的回调
            :on-remove="handleRemove"    移除已上传图片的回调
            :file-list="AddGoodsForm.pics"  展示的图片列表
             multiple  可以多选
            :before-upload="beforeJudge"  上传之前的校验
            :on-success="handleSuccess"   上传成功的回调
            :headers="UploadHeaders"   发起上传的请求头
            list-type="picture-card">  组件的展现形式
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
          </el-upload>

组件所需要的数据:

data(){
return{
        actionToUrl:'http://127.0.0.1:8888/api/private/v1/upload',
        UploadHeaders:{
          Authorization:window.sessionStorage.getItem('token')
        },
        AddGoodsForm:{
          ......
          pics:[],
        },
}
}

相关事件

进入页面时请求 此商品的数据 并且给 图片列表赋值
   async created() {
 const {data:res} = await this.$http.get(`goods/${this.NowEditId}`)
        if (res.meta.status !==200) return this.$Msg.error('获取商品相关信息失败!')
        this.AddGoodsForm = res.data
        this.AddGoodsForm.pics = this.AddGoodsForm.pics.map(x => {
          return {url:x.pics_big_url}
        })
    },

上传前判断类型和大小
      beforeJudge(file){
        console.log(file.type,file.size)
        if(!(file.type === 'image/jpeg') && !(file.type === 'image/jpg') && !(file.type === 'image/png')){
           this.$Msg.error('图片必须是:jpg/jpeg/png 格式')
           return false
        }
        if(file.size > (1024 * 500)){
          this.$Msg.error('单张图片大小不能大于500kb')
          return  false
        }
      },
点击图片预览的回调
      handlePreview2(file){
        this.PreviewPic=file.response.data.url
        this.Preview = true
      },
删除已上传图片的回调  分为删除原有的和自己上传的项  以是否有file.response属性区分
      handleRemove(file){
        console.log(file)
        // 如果删除的是 新上传的图片
      if(file.response){
        //1.获取将要删除的图片临时路径
        const fileUrl = file.response.data.url
        //2.从pics 数组中,找到这个图片对应的索引值
        let aaa = this.AddGoodsForm.pics.findIndex(value => value === fileUrl)
        //3.调用数组 splice 方法 把图片信息对象从pics 数组中移除
        this.AddGoodsForm.pics.splice(aaa,1)
      }else {
        const fileuid = file.uid
        let aaa = this.AddGoodsForm.pics.findIndex(value => value.uid === fileuid)
        this.AddGoodsForm.pics.splice(aaa,1)
      }
      },
本地上传成功后 再发送给服务器
      async handleSuccess(response){
       // 找出定义一下 新上传文件的路径地址
       const NewPicUrl = response.data.url
        // push 到预留表单位中
        this.AddGoodsForm.pics.push({uid:+new Date(),url:NewPicUrl})
        const {data:res} = await this.$http.put(`goods/${this.NowEditId}/pics`,this.AddGoodsForm.pics)
        if (res.meta.status !==200) return this.$Msg.error('更新主图失败!')
        this.$Msg.success('更新主图成功!')
      },

完成效果:

 

 

猜你喜欢

转载自blog.csdn.net/benlalagang/article/details/127707213