elementui的上传功能

496 阅读2分钟

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

elementui的图片上传并且显示图片在页面,不经过后端

<el-upload
              action="#"  
              ref='upload1'
              list-type="picture-card"
              :on-change="onChange"
              :limit="1"
              :auto-upload="false"
              :file-list="fileList"
              :http-request="httpRequest"
              :before-upload='beforeAvatarUpload'
            accept="image/png,image/gif,image/jpg,image/jpeg"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}" class="files">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
//data.return
fileList:[],
      file:'',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
​
//
show(){
      this.$refs.upload1.submit();
    },
async httpRequest(){
      let formData = new FormData()// FormData 对象
        let file = this.file.raw
        console.log(file);
        formData.append('file', file)
        var that = this
        that.$axios({
            method: 'post',
            url: url,
            headers:{'Content-Type': 'multipart/form-data'},
            data: formData
        }).then((response) => {
            console.log(response.config)
            console.log(response.data)
            if(response.data.ret) {
                // this.$message.success('上传成功')
                this.fileList = []
            }else if(response.data.msg == 'upload photo failed'){
              this.$message.error('正面照片上传失败')
              return
            }
        })
        .catch((e) => {
        })
    },
        handleRemove(file) {
      // this.$refs.upload.clearFiles();
      // console.log(file);
      this.fileList = []
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      // console.log(file);
    },
    beforeAvatarUpload(file) {
      console.log(file);
      const isJPG = file.type === 'image/jpeg' || file.type == 'image/png' || file.type == 'image/jpg' || file.raw.type == 'image/bmp';
      const isLt2M = file.size / 1024 / 1024 < 10;
​
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/png/jpg 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt2M;
    },
    onChange(file, fileList) {
      console.log(file);
      // console.log(fileList);
      this.file = file
    },

elementui的文件上传功能-上传文件-带参数-手动

<el-form :inline="true" :model="formInline" ref="formInline" class="demo-form-inline" size="mini" style="padding-right:10px;padding-left:10px;padding-top:20px;"> <el-form-item label="参数:" prop="bacth"> <el-input v-model="formInline.bacth" placeholder="内容"></el-input> </el-form-item> <el-form-item> <el-upload class="upload-demo upload-flex" ref="upload" action="#" :on-preview="handlePreview" :on-remove="handleRemove" :http-request="httpRequest" :file-list="fileList" :on-success="handSuccess" :on-change="handleChange" :on-exceed='handleExceed' :before-remove='beforeRemove' :data="getUploadList" :auto-upload="false" accept=".txt" :limit="1"> <el-button slot="trigger" size="mini" type="primary">选择文件</el-button> <el-button style="margin-left: 10px;" size="mini" type="success" @click="submitUpload">上传新数据</el-button>

​

只能上传txt文件

​

</el-upload> </el-form-item> </el-form>

<script> export default { data() { return { getNums:'' } methods: { getNum(value){ this.getNums = value }, submitUpload(data) {//点击上传 this.$refs.upload.submit(data); }, handleChange(file, fileList) {//上传文件变化时 this.fileList = fileList }, async httpRequest(param){ let file = param.file // 相当于input里取得的files let batch_name = this.formInline.bacth // console.log(file) let formData = new FormData()// FormData 对象 formData.append('file', file)// 文件对象 formData.append('batch_name', batch_name) let that = this; that.$axios({ method: 'POST', url: url, headers:{'Content-Type': 'multipart/form-data'}, data: formData }).then((response) => { // console.log(response) if(response.data.ret) { this.getBatchList(); this.$message.success('上传成功') this.chuliShow = false }else{ this.$message.error(response.data.msg+'失败') this.chuliShow = false } }) .catch((e) => { this.$message.error('上传失败') this.chuliShow = false })


    },
    handSuccess(response, file, fileList){//上传成功提示并且清除列表
        this.chuliShow = true
        this.$refs.upload.clearFiles();
        this.formInline.bacth=''
        // console.log(response, file, fileList);
    },
    handleRemove(file, fileList) {//文件移除的
        // console.log(file, fileList);
    },
    handlePreview(file) {//点击上传文件的时候的
        // console.log(file);
    },
    handleExceed(files, fileList) {//文件限制超个数
        this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {//删除
        return this.$confirm(`确定移除 ${ file.name }?`);
    },

} } </script>

elementui的文件上传限制格式和大小

第一种是accept
<el-upload
          class="upload-demo"
          action="#"
          :http-request="httpRequest"
          :on-change="onChange"
          :accept="accept"
          multiple
          :limit="1"
          ref="upload"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :auto-upload="false"
          :before-upload="beforeAvatarUpload"
          >
          <el-button slot="trigger" class="but up-but" icon="el-icon-upload2" type="primary" @click="getaccept">选取文件</el-button>
          <el-button style="margin-left: 10px;margin-top:70px;" :loading="loading" class="but" @click="submitUpload">确定提交</el-button>
        </el-upload>
常用的文件类型
let text = ['TXT','DOC','XLS','PPT','DOCX','XLSX','PPTX','pdf','txt','doc','xls','ppt','docx','xlsx','pptx','zip','rar','ZIP','RAR']
let photo = ['jpg','png','jpeg','bmp','gif','raw','JPG','PNG','JPEG','BMP','GIF','RAW','zip','rar','ZIP','RAR']
let music = ['WMA','MP3','wav','wma','mp3','WAV','zip','rar','ZIP','RAR']
let video = ['mp4','mov','avi','wmv','3gp','mkv','flv','MP4','MOV','AVI','WMV','3GP','MKV','FLV','zip','rar','ZIP','RAR']
第二种就是before-upload的方法
beforeAvatarUpload(file) {
  let type1 = (file.name).substring((file.name).lastIndexOf(".")+1)
      let type = type1.trim().toLowerCase()
      // const isJPG = type === 'jpeg' || type === 'jpg' || type === 'png';
      // const isText = type === 'doc/txt//xls/docx/xlsx' || type === 'txt' || type === 'pdf' || type === 'xls' || type === 'jpg' || type === 'jpg';
      // const isvideo = type === 'mp4/flv/zip/rar/WMA/MP3/wav';
      const isvideo = type === 'mp4' || type === 'mov' || type === 'avi' || type === 'wmv' || 
      type === '3gp' || type === 'mkv' || type === 'flv' || type === 'wma' || type === 'mp3' 
      || type === 'wav' || type === 'zip' || type === 'rar';
      const isLt50M = (file.size / 1024 / 1024) < 50;
      const isLt200M = (file.size / 1024 / 1024) < 200;
      console.log(isLt200M);
      console.log(isvideo);
      console.log(isLt50M);
      if(isvideo){
        if (!isLt200M) {
          this.$message.error('上传视频音频大小不能超过 200MB!');
          this.loading = false
          this.$refs.upload.clearFiles()
        }else{}
      }else if(!isLt50M){
        this.loading = false
        this.$message.error('上传文档图片大小不超过50MB');
        this.$refs.upload.clearFiles()
      }else{}
      return isLt200M && isvideo || isLt50M
},

欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章