AntDesign vue學習筆記-自定義文件上傳


上傳文件時實際可能需要傳輸一個token。

方法一:

1、查看vue antdesign文檔
https://vue.ant.design/components/upload-cn/

 

 

2、使用customRequest

customRequest 通過覆蓋默認的上傳行為,可以自定義自己的上傳實現 Function 

3、定義customRequest,之前定義action行為會被覆蓋,可以注釋掉

 

 

 4、customRequest代碼如下

 
         
    customRequest (data) {
      const formData = new FormData()
      formData.append('file'data.file)
      formData.append('token''aiufpaidfupipiu')//隨便寫一個token示例
      this.saveFile(formData)
    },
    saveFile (formData) {
        
        let that = this
        httpUtil.post("/snf/File/PostImportExcel"formDatares => {
                retFun(res)
        })
        
    },
 

5、這樣當文件變化時,就會附帶token並上傳到服務器,NetWork觀察提交數據如下

6、有同學反映無法接受數據,現給一個后端代碼demo(.netcore)參考,新建一個.netcore webapi工程,修改Post代碼如下。

 

 

 

 

 

7、D盤下文件保存成功如下

 

 

 

 方法二:

最近發現有一種官方例子更符合習慣思維的方法,看這個例子

<template>
  <div class="clearfix">
    <a-upload :fileList="fileList" :remove="handleRemove" :beforeUpload="beforeUpload">
      <a-button> <a-icon type="upload" /> Select File </a-button>
    </a-upload>
    <a-button
      type="primary"
      @click="handleUpload"
      :disabled="fileList.length === 0"
      :loading="uploading"
      style="margin-top: 16px"
    >
      {{ uploading ? 'Uploading' : 'Start Upload' }}
    </a-button>
  </div>
</template>
<script>
import reqwest from 'reqwest';
export default {
  data() {
    return {
      fileList: [],
      uploading: false,
    };
  },
  methods: {
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      return false;
    },
    handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files[]', file);//后面再加上token
      });
      this.uploading = true;

      // You can use any AJAX library you like
      request({
        url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
        method: 'post',
        processData: false,
        data: formData,
        success: () => {
          this.fileList = [];
          this.uploading = false;
          this.$message.success('upload successfully.');
        },
        error: () => {
          this.uploading = false;
          this.$message.error('upload failed.');
        },
      });
    },
  },
};
</script>

 


免責聲明!

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



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