简体   繁体   中英

How to send a file uploaded by javascript and get it received in a flask app and send it as post request to another server?

When i try to send a post request from flask using the file, which is received via the ajax request from client side, I am getting an exception:'too many values to unpack (expected 2)

  1. I have a client side app which uploads a file(Javascript).
  2. I have my server code which acts as a proxy which deals with all external server calls. The uploaded file gets send to this server as a post request from client side.
  3. Now i need to send this file received in my server to an external server as a post request using requests module in python.

I am stuck with an exception when i am doing step 3. I am not sure if it is the right way to post such files as i am new to flask. Please give some inputs which might help.

  1. Client side code

     $('input[type="file"]').change(function (e) { var formData = new FormData(e.target.files[0]); var fileName = e.target.files[0].name; var fileType = e.target.name; var settings = { "async": true, "crossDomain": true, "url": "/upload?file_name="+fileName+"&file_type="+fileType, "method": "POST", "contentType": false, "cache": false, "processData": false, "data": formData }; $.ajax(settings).done(function (response) { console.log(response); }); }); 
  2. Flask code

@app.route('/upload', methods=['GET','POST'])
    def uploadToExternalServer():
        if request.method == "POST":
            try:
                file_content=request.files['file']
                file_type= request.args.get('file_type')
                file_name= request.args.get('file_name')
                url="url to post with params"
                response = requests.post(url, auth=('usr', 'pwd!'),files=file_content)   
                return r
            except Exception as e:
                logging.info(e.args[0])

Expected:

Should be able to successfully post the file to the external server

Actual:

Getting an exception at post request as :'too many values to unpack (expected 2)

Check the documentation of Requests

I think your problem is that you are trying to do your post passing the file like an object, and the param expects an dictionary.

files – (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.

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