Search code examples
jquerypythonimageuploading

Image uploading to website with jquery/python


I created a website where visitors can write text in it (it is like a facebook or blog). Now I want to implement that the visitors can also upload images to the site so I have added the user interface for it: a "Browse" button and an "Upload" button.

I am using javascript/jquery in the client side and python in the server side.

How can I make that when a user clicks the browse button a dialog to select the file appears? And then how can this file be uploaded to a given path in the server? Can the client side script upload the file to the server unilaterally or is a server side script needed to accept the file?


Solution

  • I guess you are trying to upload this file asynchronously so:

    Client side

    In order to select a file you have to use inside your html:

    <input type="file" id="file">
    

    Users can select their file with this element. Now the Javascript part:

    function upload() {
        var formData = new FormData();
        var target = //Upload-Server URL
        formData.append("file", document.getElementById("file").files[0]);
        var xhr = new XMLHttpRequest();
        var eventSource = xhr.upload || xhr;
        eventSource.addEventListener("progress", function(e){
            var current = e.loaded || e.position ;
            var total = e.total || e.totalSize;
            var percant = parseInt((current/total)*100, 10);
            // DO whatever you want with progress
        });
        xhr.open("POST", target, true);
        xhr.send(formData);
        xhr.onload = function() {
            if (this.status === 200)
                // SUCCESS
        };
    }
    

    Client Side

    I do not have experience with python server side coding but this http://webpython.codepoint.net/cgi_file_upload may be useful in your case.