Flask-RESTful - Upload image

后端 未结 5 1925
再見小時候
再見小時候 2020-12-08 01:03

I was wondering on how do you upload files by creating an API service?

class UploadImage(Resource):
    def post(self, fname):
        file = request.files[\         


        
相关标签:
5条回答
  • 2020-12-08 01:31
    from flask import Flask, url_for, send_from_directory, request
    import logging, os
    from werkzeug import secure_filename
    
    app = Flask(__name__)
    file_handler = logging.FileHandler('server.log')
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    
    PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
    UPLOAD_FOLDER = '{}/uploads/'.format(PROJECT_HOME)
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    
    
    def create_new_folder(local_dir):
        newpath = local_dir
        if not os.path.exists(newpath):
            os.makedirs(newpath)
        return newpath
    
    @app.route('/', methods = ['POST'])
    def api_root():
        app.logger.info(PROJECT_HOME)
        if request.method == 'POST' and request.files['image']:
            app.logger.info(app.config['UPLOAD_FOLDER'])
            img = request.files['image']
            img_name = secure_filename(img.filename)
            create_new_folder(app.config['UPLOAD_FOLDER'])
            saved_path = os.path.join(app.config['UPLOAD_FOLDER'], img_name)
            app.logger.info("saving {}".format(saved_path))
            img.save(saved_path)
            return send_from_directory(app.config['UPLOAD_FOLDER'],img_name, as_attachment=True)
        else:
            return "Where is the image?"
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=False)
    

    Here is a link

    0 讨论(0)
  • 2020-12-08 01:41
    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

    0 讨论(0)
  • 2020-12-08 01:41

    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")
    
    0 讨论(0)
  • 2020-12-08 01:43

    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/

    0 讨论(0)
  • 2020-12-08 01:57

    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})
    
    0 讨论(0)
提交回复
热议问题