Streaming file upload using bottle (or flask or similar)

后端 未结 2 1346
囚心锁ツ
囚心锁ツ 2020-12-12 21:15

I have a REST frontend written using Python/Bottle which handles file uploads, usually large ones. The API is wirtten in such a way that:

The client sends PUT with t

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 22:04

    When using plupload solution might be like this one:

    $("#uploader").plupload({
        // General settings
        runtimes : 'html5,flash,silverlight,html4',
        url : "/uploads/",
    
        // Maximum file size
        max_file_size : '20mb',
    
        chunk_size: '128kb',
    
        // Specify what files to browse for
        filters : [
            {title : "Image files", extensions : "jpg,gif,png"},
        ],
    
        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,
    
        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },
    
        // Flash settings
        flash_swf_url : '/static/js/plupload-2.1.2/js/plupload/js/Moxie.swf',
    
        // Silverlight settings
        silverlight_xap_url : '/static/js/plupload-2.1.2/js/plupload/js/Moxie.xap'
    });
    

    And your flask-python code in such case would be similar to this:

    from werkzeug import secure_filename
    
    # Upload files
    @app.route('/uploads/', methods=['POST'])
    def results():
        content = request.files['file'].read()
        filename = secure_filename(request.values['name'])
    
        with open(filename, 'ab+') as fp:
            fp.write(content)
    
        # send response with appropriate mime type header
        return jsonify({
            "name": filename,
            "size": os.path.getsize(filename),
            "url": 'uploads/' + filename,})
    

    Plupload always sends chunks in exactly same order, from first to last, so you do not have to bother with seek or anything like that.

提交回复
热议问题