Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-RESTful - Upload image

Tags:

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!

like image 983
Sigils Avatar asked Mar 11 '15 09:03

Sigils


People also ask

How do I upload files using Flask API?

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.

How do I accept files on Flask API?

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 .


2 Answers

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") 
like image 122
Ron Harlev Avatar answered Sep 29 '22 19:09

Ron Harlev


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

like image 39
Sibelius Seraphini Avatar answered Sep 29 '22 18:09

Sibelius Seraphini