前端(vue)文件上傳


template部分

<el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          name="articleImage"
          :file-list="fileList"
          :on-success="onSuccessData"
          action="http://192.168.1.113:9305/upload/image/uploadImg"
          :before-upload="beforeUpload">
          <el-button slot="trigger" size="small" type="primary">選取文件</el-button>
          <a href="./static/moban.xlsx" rel="external nofollow" download="模板"><el-button size="small" type="success">下載模板</el-button</a>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
          <div slot="tip" class="el-upload__tip">只能上傳excel文件,且不超過5MB</div>
          <div slot="tip" class="el-upload-list__item-name">{{fileName}}</div>
</el-upload> 

如何沒有特殊要求,可以直接配置組件上傳文件,返回保存路徑

js部分

// 文件上傳成功時觸發的鈎子函數
onSuccessData(response, file, fileList) {
      console.log(response)
      console.log(file)
      console.log(fileList)
},
// 文件上傳時的驗證,自定義驗證規則,
beforeUpload(file){
      // debugger(打斷點)
      console.log(file,'文件');
      this.files = file;
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上傳模板只能是 xls、xlsx格式!')
        return
      }
      if (!isLt2M) {
        this.$message.warning('上傳模板大小不能超過 5MB!')
        return
      }
      this.fileName = file.name;
      // return false // 返回false不會自動上傳
},
// 手動上傳文件到服務器
submitUpload() {
      console.log('上傳'+this.files.name)
      if(this.fileName == ""){
        this.$message.warning('請選擇要上傳的文件!')
        return false
      }
      let fileFormData  = new FormData();
      fileFormData.append('articleImage', this.files, this.fileName);//filename是鍵,file是值,就是要傳的文件,test.zip是要傳的文件名
      let requestConfig = {
        headers: {
        'Content-Type': 'multipart/form-data'
        },
      }
      this.$axios.post(`/upload/image/uploadImg`, fileFormData, requestConfig)
      .then((res) => {
        console.log('上傳數據后返或數據')
        console.log(res)
         if (data && data.code === 0) {
           this.$message({
             message: '操作成功',
             type: 'success',
             duration: 1500,
             onClose: () => {
             this.visible = false
             this.$emit('refreshDataList')
             }
            })
        } else {
        this.$message.error(data.msg)
        }
      }) 
},


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM