Flask-RESTful - Upload image

58,378

Solution 1

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

Solution 2

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")

Solution 3

you can use the request from flask

class UploadImage(Resource):
    def post(self, fname):
        file = request.files['file']
        if file and allowed_file(file.filename):
            # From flask uploading tutorial
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file', filename=filename))
        else:
            # return error
            return {'False'}

http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

Solution 4

Something on the lines of the following code should help.

 @app.route('/upload', methods=['GET', 'POST'])
 def upload():
    if request.method == 'POST':
        file = request.files['file']
        extension = os.path.splitext(file.filename)[1]
        f_name = str(uuid.uuid4()) + extension
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], f_name))
        return json.dumps({'filename':f_name})

Solution 5

Following is a simple program to upload an image using curl and saving it locally.

from flask import Flask
from flask_restful import Resource, Api, reqparse
import werkzeug
import cv2
import numpy as np

app = Flask(__name__)
api = Api(app)

parser = reqparse.RequestParser()
parser.add_argument('file',
                    type=werkzeug.datastructures.FileStorage,
                    location='files',
                    required=True,
                    help='provide a file')

class SaveImage(Resource):
    def post(self):
        args = parser.parse_args()
        # read like a stream
        stream = args['file'].read()
        # convert to numpy array
        npimg = np.fromstring(stream, np.uint8)
        # convert numpy array to image
        img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED)
        cv2.imwrite("saved_file.jpg", img)

api.add_resource(SaveImage, '/image')

if __name__ == '__main__':
    app.run(debug=True)

You can like using curl like this:

curl localhost:port/image -F file=@image_filename.jpg

Reference

Share:
58,378

Related videos on Youtube

Sigils
Author by

Sigils

Software consultant at IT Minds

Updated on September 24, 2021

Comments

  • Sigils
    Sigils over 2 years

    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!

    • iJade
      iJade about 9 years
      try using Blue Imp jQuery File Upload github.com/blueimp/jQuery-File-Upload
    • Sigils
      Sigils about 9 years
      Hello @iJade , I am using Angular as front-end tho! But thanks for the recommendation! I only need to know how you do this at the server side! :)
  • Daryl Spitzer
    Daryl Spitzer about 7 years
    This doesn't appear to use Flask-RESTful.
  • Nabin
    Nabin over 6 years
    Not restful to me as well
  • DarkSuniuM
    DarkSuniuM over 5 years
    What's the difference between werkzeug.datastructures.FileStorage and werkzeug.FileStorage ?
  • domih
    domih over 5 years
    It should be mentioned how that API can be used: Here is a curl example: curl -v -X POST -H "Content-Type: multipart/form-data" -F "[email protected]" http://localhost:8080/api/maintenance/update Using application/octet-stream as content type did not work out for me...
  • truthadjustr
    truthadjustr over 4 years
    Skipping -H "Content-Type: multipart/form-data" worked for me
  • Maleehak
    Maleehak over 3 years
    It is not restful