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)
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.
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); }); });
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.