JavaScript file upload #4901
-
Hello, I'm trying to upload files to Flask using Javascript. On this page I can read how to do that with an HTML form. However I'm not able to do the same with pure JavaScript. To replicate:
In Flask Any help would be greatly appreciated. Environment:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Just FYI, I also suggest |
Beta Was this translation helpful? Give feedback.
-
Hello, I think I can help you with that. First, let's explain some points. In the example repository that you share you are using
Why do that? well, if you look at the FormData documentation we have this quote below:
So when using FormData we are automatically using
In other words, the browser will automatically set the Content-Type to use So we have the following code change in HTML file async function doPost() {
event.preventDefault();
const form = new FormData();
const files = document.getElementById('files').files;
for (let i = 0; i < files.length; i++) {
form.append(`file`, files[i]);
}
const response = await fetch('/post', {
method: 'POST',
body: form,
// headers: {'Content-Type': 'multipart/form-data'}, REMOVE THIS
});
} The rest of the HTML code no needs changes. Okay, now we need to make some changes to your flask code. But first, let's move on to another point, to understand other behavior you've faced earlier.
Well, let's start with the most complex, According to the official Flask Request documentation we have this behavior regarding the
In other words, if the Content-Type is defined correctly, being a format known by the library ( In nutshell,
Ok, now the
In the Upload File examples we can also see this. So it only remains to make some changes to the API code. As mentioned, we use request.files, so we have the following code def create_app() -> Flask:
app = Flask(__name__)
app.config['CONTENT_TYPE'] = 'multipart/form-data' # add this configuration to define the type of data received by the API (note that content-type is not manually specified in HTML file, only here, in the Flask API python file)
@app.get('/')
def get() -> str:
return render_template('test.html')
@app.post('/post')
def post() -> str:
files = request.files.getlist('file') # get list of uploaded files
# files = request.files['files'] # another syntax to get list of uploaded files
# read files
for file in files:
file_bytes = file.read() # read de file bytes
print(file_bytes)
return ''
return app I hope it helps. |
Beta Was this translation helpful? Give feedback.
Hello, I think I can help you with that. First, let's explain some points. In the example repository that you share you are using
fetch
andFormData
to make request to FlaskAPI. Given this, we have the first point:headers
option from fetch request.Why do that? well, if you look at the FormData documentation we have this quote below:
So when using FormData we are automatically using
multipart/form-data
. But, also in theFormData
documentation, we have this warning: