简体   繁体   中英

How to send file metadata over api using fetch

In a web-app that I am developing, users can upload files. As part of the upload process, users must specify what type of file (eg invoice, receipt, contract) it is and also who the customer is.

I then send the file to the backend server using a fetch. From the back-end server, it is to be uploaded to an ftp. On the ftp I need to create a directory based on the file type id and customer id. for example, it should be in the directory ftp/invoices/kfc.

Then, on a database, the server registers the file, its location and, for example, it's upload date.

Ideally I want to send the metadata (type of file, customer) as part of the same fetch.

My backend server is using python and flask.

My frontend code is below. I've tried a couple of things already:

  • I've tried adding the metaData as a formData element, but flask does not like this and throws a 400 error when I try to read it.
  • I've also considered doing a two-step process of first sending the metaData and then the file (or the other way around), but this seems more complicated than it needs to be.
  • I've also tried adding the metaData as headers to the api request, but then I run into cors complications that I'd prefer to avoid.
  • I've tried creating the metaData as a additional simple json file to send with the formData, but it is not obvious to me how to "create a file on the fly" in a front-end React app. Maybe it's no big deal?
  • I've also spent some time searching the internet for a solution, but nothing really matched what I was trying to do (which seems suspicious)

I'm hoping someone can tell me there's an easy way to do this.

The frontend is React-redux, the backend python and flask and the database in MySQL

case 'SEND_FILE_TO_SERVER':
        const formData = new FormData();           
        
        formData.append('File', action.fileToSend);

        fetch(window.location.origin + '/api/submit-file', {
            method: 'POST',
            body: formData,
        }) 

After some more troubleshooting, I found that the correct approach was indeed to add the metaData to the formData. The reason it had not worked at first was because I was trying to access it wrongly in python flask. So, in javascript you should have

formData.append('File', action.fileToSend);
formData.append('metaData', JSON.stringify(action.metaData));

and then in python flask you should have

@app.route('/api/submit-file', methods=["POST"])
def submit_file():
    file = request.files['File']
    metaData = loads(request.form['metaData'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM