'Uploading file gets bad request error in flask
I want to upload a file from angular as frontend to flask as backend, but every time I upload a file I always get an error like the following
werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'flag_icon'
I've tried several ways from the internet and youtube but still can't find the solution, can anyone help me?
Here's the HTML form in angular that I'm using
<form class="form-body" enctype="multipart/form-data">
<div class="form-group">
<label for="flag_icon">{{used_lang.lable_currflag}}</label>
<input class="form-control form-control-lg mb-3"
type="file"
id="flag_icon"
name="flag_icon"
(change)="flagIconChange($event)"
accept="image/*"
disabled
required>
</div>
</form>
Here's the program code that I wrote in the ts file
flagIconChange(event: any) {
const file:File = event.target.files[0];
if (file) {
const formData = new FormData();
formData.append("flag_icon", file);
this.backendAPI.flagIconUpdate(formData).subscribe((res: any) => {console.log(res)});
}
}
The following is the program code for the service API that I use
uploadFile = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data', 'Cache-Control': 'no-cache', 'Pragma': 'no-cache',
"Accept": "multipart/form-data"
})
}
flagIconUpdate(data: any): Observable<any>{
return this.httpClient.post(this.baseAPI + '/forex/flag_icon', data, this.uploadFile)
.pipe(catchError(this.errorHandler));
}
Here's the program code on flask
@app.route('/forex/flag_icon', methods=['POST'])
def forexFlagIconUpload():
if request.method == 'POST':
flag_name = request.files["flag_icon"]
return jsonify({'status': flag_name.filename}),200
Solution 1:[1]
I am not sure but try to use request.form["flag_icon"] instead of request.files["flag_icon"] as you are sending a form with the file inside as a input
@app.route('/forex/flag_icon', methods=['POST'])
def forexFlagIconUpload():
if request.method == 'POST':
flag_name = request.files["flag_icon"]
return jsonify({'status': flag_name.filename}),200
to:
@app.route('/forex/flag_icon', methods=['POST'])
def forexFlagIconUpload():
if request.method == 'POST':
flag_name = request.files["flag_icon"]
return jsonify({'status': flag_name.filename}),200
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asdat 3 |
