I was wondering on how do you upload files by creating an API service?
class UploadImage(Resource): def post(self, fname): file = request.files['file'] if file: # save image else: # return error return {'False'}
Route
api.add_resource(UploadImage, '/api/uploadimage/<string:fname>')
And then the HTML
<input type="file" name="file">
I have enabled CORS on the server side
I am using angular.js as front-end and ng-upload if that matters, but can use CURL statements too!
Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.
In your API backend, you will receive the file by using file = request. files['file'] . The name "file" comes from the name of the input tag in the HTML Form you are using to send the file to your backend. In this example, the backend is saving the uploaded files to UPLOAD_FOLDER .
The following is enough to save the uploaded file:
from flask import Flask from flask_restful import Resource, Api, reqparse import werkzeug class UploadImage(Resource): def post(self): parse = reqparse.RequestParser() parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files') args = parse.parse_args() image_file = args['file'] image_file.save("your_file_name.jpg")
class UploadWavAPI(Resource): def post(self): parse = reqparse.RequestParser() parse.add_argument('audio', type=werkzeug.FileStorage, location='files') args = parse.parse_args() stream = args['audio'].stream wav_file = wave.open(stream, 'rb') signal = wav_file.readframes(-1) signal = np.fromstring(signal, 'Int16') fs = wav_file.getframerate() wav_file.close()
You should process the stream, if it was a wav, the code above works. For an image, you should store on the database or upload to AWS S3 or Google Storage
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With