web-dev-qa-db-fra.com

Flask-RESTful - Télécharger une image

Je me demandais comment télécharger des fichiers en créant un 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>')

Et puis le HTML

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

J'ai activé CORS côté serveur

J'utilise angular.js comme front-end et ng-upload si c'est important, mais je peux aussi utiliser les instructions CURL!

10
Sigils
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()

Vous devez traiter le flux. S'il s'agissait d'un fichier wav, le code ci-dessus fonctionne . Pour une image, vous devez le stocker dans la base de données ou le télécharger sur AWS S3 ou Google Storage.

13
Sibelius Seraphini

Ce qui suit est suffisant pour enregistrer le fichier téléchargé

    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")
9
Ron Harlev

Quelque chose sur les lignes du code suivant devrait aider.

 @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})
6
iJade

vous pouvez utiliser la demande du flacon

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/

3
Jethro Guce
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 __== '__main__':
    app.run(Host='0.0.0.0', debug=False)

Voici un lien

0
Mudidi Jimmy