“This is the 11th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

Author: Tangyuan

Personal blog: Javalover.cc

preface

There are two methods for uploading files to the cloud storage system: front-end upload and back-end upload.

Front-end upload means that the front-end uploads to the OSS cloud storage and sends the remote link to the back-end.

Back-end upload means that the front-end is only responsible for uploading local files, and then the back-end can upload them to cloud storage or local storage.

Because the official example of ANDTV is introduced in the second way, so we will introduce the first way, front-end upload to cloud storage;

The Upload component of Ant Design Vue is used here;

directory

  1. Component is introduced
  2. Upload the example
  3. Record on pit

The body of the

1. Components

The Upload component has many properties, so we’ll just focus on the following:

parameter instructions type The default value
accept For details about the types of files that can be uploaded, seeinput accept Attribute string There is no
action Upload address string|(file) => Promise There is no
beforeUpload The hook before uploading a file. The parameter is the uploaded filefalseStop uploading. (file, fileList) => `boolean Promise`
customRequest Overrides the default upload behavior and implements its own upload mode Function There is no
remove Click the callback to remove the file, not remove it if the return value is false Function(file): `boolean Promise`
multiple Whether multiple files are supported boolean false
fileList List of uploaded files object[] There is no
  • Accept: Since we only need to upload PDF files for this article, we need to accept=.pdf
  • Action: accepts a backend address as the property value. The local file will be uploaded to the specified address for processing.
  • BeforeUpload: This property is triggered after the file is selected but before the file is uploaded. The main purpose here is to get a list of uploaded files
  • CustomRequest: It is the core of this article, which overwrites the original action operation and realizes the specific upload mode by itself, such as uploading to Ali Cloud and other clouds
  • FileList: displays the list of uploaded files with beforeUpload

The Upload component has a hidden element inside that displays a list of files that have been uploaded;

This element is not displayed when no file is uploaded.

When a file is uploaded, this element displays a list of uploaded files.

2. Upload examples

Let’s start with the custom upload example. The code only shows the key parts

The HTML section is as follows:

<a-upload accept=".pdf" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload" :customRequest="handleUpload"> <a-button> < A-icon type="upload" /> Click to upload a file (PDF format only) </a-button> </a-button>Copy the code

The js part is as follows:

handleRemove(file) {
    const index = this.fileList.indexOf(file);
    const newFileList = this.fileList.slice();
    newFileList.splice(index, 1);
    this.fileList = newFileList;
},

beforeUpload(file, fileList) {
    this.fileList = fileList
    console.log('file:', file)
    console.log('fileList:', fileList)
    return true;
},

handleUpload(data) {
    console.log(data)
    const _this = this
    const file = data.file
    if(file){
        client.put('pdf/'+file.name, file).then(res= >{
            console.log(Results: ', res)
            _this.detailNew = Object.assign({}, this.detailNew, {filePath: res.url})
        })
    }else{
        console.error('No file selected')}},Copy the code

Ali cloud upload interface, other cloud storage interface is similar, is to create a client object, and then introduced where needed

import OSS from 'ali-oss';
const client=new OSS({
    region: '* * *'.accessKeyId: '* * *'.accessKeySecret: '* * *'.bucket: '* * *'
})

export {client}
Copy the code

Then, when submitting the form, simply submit the this.DetailNew object by POST, which contains the cloud storage path of the file

3. Records of trampling pits

  1. CustomRequest assignment problem

If you assign the attribute customRequest to handleUpload(data) instead of the function name handleUpload;

Each time a vue property is refreshed, the handleUpload(data) function is triggered.

This is because instead of assigning a function to customRequest, you assign a block of code to the function.

When the view is initialized, a function execution is triggered.

And then it fires again and again as the view refreshes later;

When you upload a file, you will receive an error 400 because the customRequest is no longer a custom file upload attribute, so the system will find the default file upload path.

CustomRequest is assigned to a function name instead of a function name + parameter. Otherwise, the value of this property becomes a block of execution code for the function, which is then automatically executed every time it fires

The question here is why not make customRequest an event? Events feel more reasonable; It feels like all of the above properties can be set to events

  1. BeforeUpload return value issue

BeforeUpload returns a value of false to stop uploading;

At first I understood to stop the default upload, so I returned false;

Then when I uploaded the file, I found that the custom upload in the customRequest could not be triggered.

False: stop all subsequent uploads, including default uploads and custom uploads.

Solution: Set false to return only when no files need to be uploaded. Test more, understand more;

  1. The upload progress is not displayed

This is because we are using a custom upload mode, so the default upload schedule is invalid;

The default upload progress can listen for the change event in @change, and then process it according to the response of the server after the file is uploaded. If 200 is returned, it succeeds; if error is returned, it fails.

Therefore, we need to implement the loading schedule by ourselves. We can directly add a loading attribute to the upload button:

  • Set to true to start uploading;

  • Set to false when the upload is complete.

<a-button  :loading="loading"> <a-icon type="upload" />Click upload file (PDF only)</a-button>
Copy the code

Set to true in beforeUpload:

beforeUpload(file, fileList) {
    this.fileList = fileList
    console.log('file:', file)
    console.log('fileList:', fileList)
    this.loading = true
    return true;
},
Copy the code

After uploading to Aliyun, set it to false:

handleUpload(data) {
    console.log(data)
    const _this = this
    const file = data.file
    if(file){
        client.put('pdf/'+file.name, file).then(res= >{
            console.log(Results: ', res)
            _this.detailNew = Object.assign({}, this.detailNew, {filePath: res.url})
            _this.loading = false})}else{
        console.error('No file selected')}},Copy the code

conclusion

This paper mainly introduces the antDV Upload component to achieve a custom file to the cloud storage method, the core is the customRequest attribute;

The default upload is actually the most convenient, the front end only needs to pass local files to the back end, the back end to upload files to various clouds;

But it takes coordination;