简体   繁体   中英

Flask, serving Static File and or folder inside Javascript

I m trying to insert the following static url for a static folder inside a javascript so it can properly load a saved file, but im still facing error.

Here is what happens.

the normal file location is http://localhost/static/uploads/filename.ext but with the following javascript, it fetch the location based on the views' url_prefix='/media' hence the url it fetches is http://localhost/media/static/uploads/filename.ext

here is the following code:

    <script>
$(function(){
        $('#fileupload').fileupload({
            url: 'upload',
            dataType: 'json',
            add: function (e, data) {
                data.submit();
            },
            success:function(response,status) {
            console.log(response.filename);
            var filePath = 'static/uploads/' + response.filename;

            $('#imgUpload').attr('src',filePath);
            $('#filePath').val(filePath);
                console.log('success');
            },
            error:function(error){
                console.log(error);
            }
        });
})

I m trying to replace,

var filePath = 'static/uploads/' + response.filename;

with

var filePath =  {{ url_for('static', filename='/uploads/') }} + response.filename;

but with no success. The original filename settings leads to the Blueprint url_prefix, which i wanted to bypass.

Edit

Here is my Views

@media.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})

There are two paths to consider here and you need to pay close attention to which you're using where:

  1. the absolute filepath on the server eg: /opt/myapp/media/upload/<filename> , and
  2. the relative urlpath on the client eg: https://localhost/static/upload/<filename>

Your easiest solution may be to simply return the filename, without any directory preamples, then prepend the appropriate directory for the context in which you use it.

So in the python you can still return 'somefile.jpg' with:

return json.dumps({'filename': f_name})

And in the javascript you can reference '/static/uploads/somefile.jpg' with:

var filepath = '/static/uploads/' + response.filename;

Well, I have fixed the issue, I have stripped the url_prefix parameters so i can call from the root url path. to avoid the previous issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM