phenom_aks
phenom_aks

Reputation: 77

How to show images on web pages using Ajax in Flask?

I am a newbie in Python Flask. Although, I have done this task multiple time in PHP/Java, somehow I am stuck here.

My task is to upload the image onto server, then display the image on web page, do some processing on image and again display the processed image on client machine.

To this end, I am using the code at flask-fileupload-ajax-example on Github. I am able to show the filename as well as its size correctly using ajax on the web page. But, somehow, when I try to set the src of <img> tag by the path of the uploaded images, it gives a 404, File not found error.

Following are the relevant code snippets.

In app.py

@app.route('/uploadajax', methods=['POST', 'GET'])
def upldfile():
    if request.method == 'POST':
        files = request.files['file']
        print(files)
        if files and allowed_file(files.filename):
            filename = secure_filename(files.filename)
            app.logger.info('FileName: ' + filename)
            print('FileName: ' + filename)
            updir = os.path.join(basedir, 'upload/')
            files.save(os.path.join(updir, filename))
            file_size = os.path.getsize(os.path.join(updir, filename))
            file_path = '/'.join(['upload', filename])
            return jsonify(name=filename, path=file_path, size=file_size)

In app.js file:

$('#submit').click(function() {
    event.preventDefault();
    var form_data = new FormData($('#uploadform')[0]);
    $.ajax({
        type: 'POST',
        url: '/uploadajax',
        data: form_data,
        contentType: false,
        processData: false,
        dataType: 'json'
    }).done(function(data, textStatus, jqXHR){
        console.log(data);
        console.log(textStatus);
        console.log(jqXHR);
        console.log('Success!');
        $("#resultFilename").text(data['name']); // name of the file
        $("#resultFilesize").text(data['size']); // size of the file
        //my_url = "{{ url_for('upload', filename="+data['name']+" }}";
        $("#image").attr('src', data['path']); // setting the src attribute of img tag
        $("#adv-btn").attr('value', data['name']);
        $("#adv-btn").show();
        //get_image(data['name'])
    }).fail(function(data){
        alert('error!');
    });
});

I have also tried using url_for but it's not getting rendered. Any suggestion will be hugely appreciated. Thanks.

Upvotes: 0

Views: 3410

Answers (1)

Gioachino Bartolotta
Gioachino Bartolotta

Reputation: 123

Try something like this Create a folder called static under the root of your application, and move your upload folder in there.

Then define your application like this

app = Flask(__name__, static_url_path="/static", static_folder="static")
app.config["UPLOAD_FOLDER"] = "/root_flask_app/static/upload/"

Then inside app.py try:

updir = app.config["UPLOAD_FOLDER"]

and inside app.js:

$("#image").attr('src', '/static/'+data['path']);

Upvotes: 1

Related Questions