When uploading a file with Angular to a Flask backend, you can access the request data containing the uploaded file using the request
object provided by Flask. The uploaded file will be available in the request.files
attribute. Additionally, any other form data or query parameters can be accessed using request.form
and request.args
, respectively.
Here's how you can access the uploaded file and other data in Flask:
Angular (HTML):
html<form (ngSubmit)="onSubmit()" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="name">
<button type="submit">Upload</button>
</form>
Angular (Component):
typescriptimport { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-upload',
templateUrl: './upload.component.html'
})
export class UploadComponent {
constructor(private http: HttpClient) {}
onSubmit() {
const formData = new FormData();
formData.append('file', this.fileInput.nativeElement.files[0]);
formData.append('name', 'Some name'); // Additional form data
this.http.post('/upload', formData).subscribe(
(response) => {
console.log('File uploaded successfully!', response);
},
(error) => {
console.error('Error uploading file:', error);
}
);
}
}
Flask:
pythonfrom flask import Flask, request
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
name = request.form['name']
# Save the uploaded file (optional)
# file.save('path/to/save/' + file.filename)
# Process the file and other data as needed
# ...
return 'File uploaded successfully!'
if __name__ == '__main__':
app.run()
In the Flask route /upload
, we access the uploaded file using request.files['file']
, which retrieves the file object from the request data. We also access other form data like the name
input using request.form['name']
.
Remember to add error handling and file processing logic as per your application's requirements.
Make sure to include the necessary imports and dependencies in both Angular and Flask to handle file uploads and HTTP requests properly.