简体   繁体   English

Flask-RESTful - 上传图片

[英]Flask-RESTful - Upload image

I was wondering on how do you upload files by creating an API service?我想知道如何通过创建 API 服务来上传文件?

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然后是 HTML

   <input type="file" name="file">

I have enabled CORS on the server side我在服务器端启用了 CORS

I am using angular.js as front-end and ng-upload if that matters, but can use CURL statements too!如果重要的话,我使用 angular.js 作为前端和ng-upload ,但也可以使用 CURL 语句!

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.您应该处理流,如果它是 wav,则上面的代码有效。 For an image, you should store on the database or upload to AWS S3 or Google Storage对于图像,您应该存储在数据库中或上传到 AWS S3 或 Google Storage

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

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/ http://flask.pocoo.org/docs/0.12/patterns/fileuploads/

Following is a simple program to upload an image using curl and saving it locally.以下是一个使用 curl 上传图像并将其保存在本地的简单程序。

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:

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

Reference 参考

I was wondering on how do you upload files by creating an API service?我想知道如何通过创建API服务来上传文件?

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然后是HTML

   <input type="file" name="file">

I have enabled CORS on the server side我已经在服务器端启用了CORS

I am using angular.js as front-end and ng-upload if that matters, but can use CURL statements too!如果重要的话,我正在使用angular.js作为前端和ng-upload ,但是也可以使用CURL语句!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM