Flask-RESTful - 上传图片

Posted

技术标签:

【中文标题】Flask-RESTful - 上传图片【英文标题】:Flask-RESTful - Upload image 【发布时间】:2015-05-13 00:39:35 【问题描述】:

我想知道如何通过创建 API 服务来上传文件?

class UploadImage(Resource):
    def post(self, fname):
        file = request.files['file']
        if file:
            # save image
        else:
            # return error
            return 'False'

路线

api.add_resource(UploadImage, '/api/uploadimage/<string:fname>')

然后是 html

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

我在服务器端启用了 CORS

我使用 angular.js 作为前端和 ng-upload 如果这很重要,但也可以使用 CURL 语句!

【问题讨论】:

尝试使用 Blue Imp jQuery File Upload github.com/blueimp/jQuery-File-Upload 你好@iJade,我正在使用 Angular 作为前端!不过谢谢推荐!我只需要知道您如何在服务器端执行此操作! :) 【参考方案1】:

以下内容足以保存上传的文件:

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

【讨论】:

werkzeug.datastructures.FileStoragewerkzeug.FileStorage有什么区别? 应该提到如何使用该 API:这是一个 curl 示例:curl -v -X POST -H "Content-Type: multipart/form-data" -F "file=@test.zip" http://localhost:8080/api/maintenance/update 使用 application/octet-stream 作为内容类型对我来说不起作用...跨度> 跳过-H "Content-Type: multipart/form-data" 为我工作【参考方案2】:
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()

你应该处理流,如果它是一个 wav,上面的代码可以工作。 对于图像,您应该存储在数据库中或上传到 AWS S3 或 Google Storage

【讨论】:

【参考方案3】:

以下代码行中的某些内容应该会有所帮助。

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

【讨论】:

这似乎没有使用 Flask-RESTful。 我也不放心 不平静【参考方案4】:

你可以使用来自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/

【讨论】:

【参考方案5】:

下面是一个使用 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)

你可以像这样使用 curl:

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

Reference

【讨论】:

【参考方案6】:
#Image(s) and file Upload
from flask import Flask, json, request, jsonify
import os
import urllib.request
from werkzeug.utils import secure_filename

app = Flask(__name__)

app.secret_key = "caircocoders-ednalan"

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/api/upload', methods=['POST'])
def upload_image():
    if 'image' not in request.files:
        resp = jsonify(
            'status' : False,
            'message' : 'Image is not defined')
        resp.status_code = 400
        return resp

    files = request.files.getlist('image')

    errors = 
    success = False

for photo in files:

    if photo and allowed_file(photo.filename):
        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        success = True
    else:
        errors[photo.filename] = 'Image type is not allowed'

if success and errors:
    errors['message'] = jsonify(
        'data' : photo.filename,
        'status' : True,
        'message' : 'Image(s) successfully uploaded')
    resp = jsonify(errors)
    resp.status_code = 500
    return resp

if success:
    resp = jsonify(
        'data' : photo.filename,
        'status' : True,
        'message' : 'Images successfully uploaded')
    resp.status_code = 201
    return resp
else:
    resp = jsonify(errors)
    resp.status_code = 500
    return resp

【讨论】:

以上是关于Flask-RESTful - 上传图片的主要内容,如果未能解决你的问题,请参考以下文章

新手 想问下,上传图片到FastDfs后,如何在该虚拟机下找到上传的图片

怎样向网站上传图片

ASP.NET上传控件上传图片

我本地的图片怎么上传上去?就是图片要弄地址?

PHP Fckeditor 上传图片的问题

php 在多个上传图片时 怎么获取 要上传的图片宽高