Django上传图片

// start file upload see example http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
    var files;
    function prepareUpload(event) {
        files = event.target.files;
    }
    $('input[id=img]').on('change', prepareUpload);
    $('#img').live('change', uploadFiles);
    function uploadFiles(event) {
        console.log("start uploadfiles...........");
        event.stopPropagation(); // Stop stuff happening
        event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
        var data = new FormData();
        //data['0'] = files[0];
        $.each(files, function (key, value) {
            data.append(key, value);
        });
        $.ajax({
            url: '/api/postimage/',
            type: 'POST',
            data: data,
            cache: false,
            dataType: 'json',
            processData: false, // Don't process the files
            contentType: false, // Set content type to false as jQuery will tell the server its a query string request
            success: function (data, textStatus, jqXHR) {
                console.log(data.id);
                jQuery("#hiddenimg").val(data.id);

                if (typeof data.error === 'undefined') {
// Success so call function to process the form
                    //submitForm(event, data);
                    console.log("img", data)
                }
                else {
// Handle errors here
                    console.log('ERRORS: ' + data.error);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
                console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
            }
        });
    }
    // end file upload



你可能感兴趣的:(Django上传图片)