美文网首页
vue项目使用elementui组件上传文件

vue项目使用elementui组件上传文件

作者: 陶菇凉 | 来源:发表于2021-01-28 08:45 被阅读0次
    1.上传图片
    <el-upload
                    action
                    list-type="picture"
                    :on-change="loadJsonFromFilelogo"
                    style="display: inline-block;"
                    :show-file-list="false"
                    accept="image/png, image/jpg,image/gif,image/bmp,image/jpeg"
                    name="upfile"
                    :http-request="uploadFile"
                  >
                    <el-button size="small">选择文件</el-button>
       </el-upload>
    

    data定义字段

      logo_img: '',
          srcList: [],
          filelogo: ''
    

    methods方法

    methods: {
         // 获取文件信息
        uploadFile(file) {
          this.filelogo = file.file;
        },
        // 获取logo文件信息
        loadJsonFromFilelogo(file, fileList) {
          const isLt2K = file.raw.size / 1024 < 200;
          if (!isLt2K) {
            this.$message.error('上传LOGO图片大小不能超过 200K!');
            return false;
          }
          this.logo_img = file.url;
          this.filelogo = file.raw;
          this.srcList.push(this.logo_img);
        },
        //上传文件
        submitForm(formName) {
          this.$refs[formName].validate(valid => {
            if (valid) {
              if (this.filelogo) {
                this.uploadForm.append('nav_logo', this.filelogo);
              }
              var placard_show = this.navForm.placard_show === 'True' ? 'on' : '';
              var sys_placard = this.navForm.sys_placard;
              this.uploadForm.append('placard_show', placard_show);
              this.uploadForm.append('sys_placard', sys_placard);
             //提交数据的方法
              this.getsysNavPostData(this.uploadForm);
            } else {
              return false;
            }
          });
        },
    }
    

    注意el-upload标签中绑定的action不需要写路径,如果写了官方的路径会报跨域的错误。

    2.上传文件
     <el-form-item label="上传文件">
              <el-upload
                class="upload-demo"
                action
                :file-list="fileList"
                :http-request="uploadFile"
                :on-change="loadJsonFromFile"
                accept="application/vnd.ms-excel"
              >
                <el-button size="small" type="primary">
                  <span class="iconfont iconshangchuanyunduan" />
                  选择表格文件
                </el-button>
              </el-upload>
            </el-form-item>
    
    export default {
      data() {
        return {
          form: {},
          fileList: [],
          file: '',
          // 文件形式
          uploadForm: new FormData(),
          loading: false
        }
      },
      methods: {
        onSubmit() {
          if (this.fileList.length === 0) {
            this.$message.error('请选择导入文件')
            return false
          }
          this.uploadForm = new FormData()
          this.uploadForm.append('file', this.file)
          //提交数据
          this.importUserData(this.uploadForm)
        },
        // 获取文件信息
        loadJsonFromFile(file, fileList) {
          this.file = file.raw
          this.fileList = fileList
          if (this.fileList.length > 1) {
            this.fileList.splice(0, 1)
          }
        },
        // 获取文件信息
        uploadFile(file) {
          this.file = file.file
        },
      }
    }
    
    3.多个文件上传的时候进行文件的限制

    原本是有个属性:file-list="imageList、:limit="5" ",直接绑定你的数据列表既可了,但是它竟然不生效,后台研究发现要使用:on-exceed="exceed" // 上传图片超出数量限制时的钩子进行限制

    // 上传图片超出数量限制时的钩子,此方法不会返回fileList的值
        exceed(files){
              this.$message.error('最多上传3张图片哦!')
        },
    
    4.他人的方法,相比较我更详细,记录下
    <el-upload
                  :action="actionUrl"   // 图片上传地址
                  :headers="headers"   // 因为上传时需要token,所以需要自定义headers
                  :before-upload="beforeUpload"   // 文件上传前的钩子,可以在这个钩子函数里判断上传的图片的类型和大小是否达标
                  :limit="5"   // 上传图片的个数限制
                  :on-exceed="exceed"   // 上传图片超出数量限制时的钩子
                  :on-success="uploadSuccess"  // 上传成功时的钩子
                  :on-remove="fileRemove"     // 文件列表移除文件时的钩子,也就是删除图片时会触发的钩子
                  :file-list="imageList"   // 上传的文件列表,就是这个坑,下边会细说
                  accept=".jpg, .jpeg, .png, .gif"   // 接受的图片类型
                  list-type="picture-card"   // 文件列表的类型
                  >
    
    methods:{
          //获取商品信息
        getGoodsInfo(){
          this.$http.get(`/scyyGoodsStore/${this.id}`).then(({data:res}) => {
              if(res.code !== 200){
                return this.$message.error(res.msg);
              }
              this.form = {
                ...this.form,
                ...res.data
              }
              let imgList = this.form.imageVoList
              imgList.forEach( item => {
                this.imageList.push({
                  id:item.id,
                  url:item.imageUrl
                })
              })
          })
        },
        // 上传图片超出数量限制时的钩子
        exceed(files, fileList){
              this.$message.error('最多上传5张图片哦!')
        },
        // 文件上传前的钩子,数为上传的文件
         beforeUpload(file) {
              // 判断图片是否大于2M
              const isLt2M = file.size /1024/1024 < 2;
              // const fileType = file.name.substring(file.name.lastIndexOf('.')+1)
              // 判断图片的类型
              const isJpg = file.type ==  'image/jpeg' || file.type == 'image/jpg' || file.type == 'image/png' || file.type == 'image/gif'
              if(!isJpg){
                  this.$message.error('只能上传jpg, jpeg, png, gif格式的图片!')
                  return false
              }
              if (!isLt2M) {
                  this.$message.error('上传图片大小不能超过 2MB!');
                  return false
              }
          },
          // 上传成功时的钩子
          uploadSuccess(res,file,fileList){
            if(res.code !== 200){
                return this.$message.error(res.msg)
            }
            this.imageList.push(res.data)
            let formImgList = []
            this.imageList.forEach(item => {
              formImgList.push({
                id:item.id,
                imageType:0
              })
            })
            this.form.listUploadId = formImgList
          },
          // 文件列表移除文件时的钩子
          fileRemove(file, fileList){
              this.imageList= fileList
              const list = []
              this.imageList.forEach(item => {
                  list.push({
                    id:item.id,
                    imageType:0
                  })
              })
              this.form.listUploadId = list
          }
    }
    

    相关文章

      网友评论

          本文标题:vue项目使用elementui组件上传文件

          本文链接:https://www.haomeiwen.com/subject/qduozktx.html