Issue
i am trying to upload a form data in js into my flask server but i am not getting file in the server.
My code in JS is:
const form = document.forms.namedItem('fileinfo')
form.addEventListener('submit', async (event) => {
event.preventDefault()
let formData = new FormData(form)
formData.append('firstName', 'John')
let file1 = document.getElementById('fileInput').files[0]
console.log(formData)
let response = await fetch('http://127.0.0.1:5000/stateUpload', {
method: 'POST',
body: formData,
})
let _response = await response.json()
})
and this is my flask code:
@app.route("/stateUpload", methods=[ "POST"])
def stateUpload():
_data = request.form.to_dict(flat=False)
print("this is form data")
print(_data)
return "JSON File successfully uploaded"
This is my output in console in server when i press submit button:
this is form data
{'firstName': ['John']}
and this is my output in front end:
i am not able to get this file in the flask
Solution
In contrast to normal form fields, which can be accessed via request.form
, it is necessary to use request.files
on the server side in order to receive transmitted files. Here you can request an object of type FileStorage using the name of the form field.
@app.route("/stateUpload", methods=[ "POST"])
def stateUpload():
_data = request.form.to_dict(flat=False)
print("this is form data")
print(_data)
file = request.files.get('file')
print(file)
return "JSON File successfully uploaded"
The documentation for uploading files can be found here.
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.