Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

On client side: You can use the HTML5 File API which allows you to create applications that let the user interact with files locally. Basically, you can load files and render them in the browser without actually having to upload the files. Then send it via ajax to server to save it

uploadImage(e){
        var reader = new FileReader();
        var url;
        reader.onload = function(event){
            url = event.target.result;
            $('#destination').html("<img src='"+url+"' />");

            //save
            $.ajax('/api/image', {
               cache: false,
               method: 'POST',
               data: {url}
            });
        }

        //when the file is read it triggers the onload event above.
        reader.readAsDataURL(e.target.files[0]);

    }

Here is a demo

On server side:

        image = self.request.body
        import uuid
        unique_filename = str(uuid.uuid4())
        fh = open("images/"+unique_filename+".png", "wb")
        from base64 import decodestring
        fh.write(decodestring(image))
        fh.close()
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top