wake-up-neo.com

Flask-RESTful - Bild hochladen

Ich habe mich gefragt, wie Sie Dateien hochladen, indem Sie einen API-Dienst erstellen.

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

Und dann das HTML

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

Ich habe CORS auf der Serverseite aktiviert

Ich benutze angle.js als Frontend und ng-upload wenn das wichtig ist, aber ich kann auch CURL-Anweisungen verwenden!

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

Sie sollten den Stream verarbeiten, wenn es sich um eine WAV-Datei handelt, funktioniert der obige Code .. Für ein Bild sollten Sie es in der Datenbank speichern oder zu AWS S3 oder Google Storage hochladen

13

Folgendes reicht aus, um die hochgeladene Datei zu speichern

    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

Etwas in den Zeilen des folgenden Codes sollte helfen.

 @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

sie können die Anfrage aus der Flasche verwenden

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)

Hier ist ein Link

0
Mudidi Jimmy