Python Flask-RESTful - 上传图片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28982974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:58:16  来源:igfitidea点击:

Flask-RESTful - Upload image

pythonflaskflask-restful

提问by Sigils

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-uploadif that matters, but can use CURL statements too!

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

采纳答案by Sibelius Seraphini

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

您应该处理流,如果它是 wav,则上面的代码有效。对于图像,您应该存储在数据库中或上传到 AWS S3 或 Google Storage

回答by iJade

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

回答by Ron Harlev

The following is enough to save the uploaded file

以下足以保存上传的文件

    from flask import Flask
    from flask_restful import Resource, Api, reqparse
    import werkzeug

    class UploadAudio(Resource):
      def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files')
        args = parse.parse_args()
        audioFile = args['file']
        audioFile.save("your_file_name.jpg")

回答by Jethro Guce

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/

回答by Mudidi Jimmy

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

这是一个链接