使用jQuery

时间:2015-12-17 05:16:08

标签: jquery ajax jquery-file-upload

有没有办法在JSP + java中使用jQuery上传multipart文件。 在jQuery AJAX中执行时出错。

$.ajax({
    type: "POST",
    url: "${pageContext.request.contextPath}/users/imageUpload/" + $imageUpload + "/" + $userId‌​,
    contentType: "multipart/form-data",
    processData: false,
}).done(function(data) {}).fail(function(data) {
    alert("Ooopss..! Something Bad Happened.!");
});

2 个答案:

答案 0 :(得分:5)

$("input:file").change(function(objEvent) {
    var objFormData = new FormData();
    // GET FILE OBJECT 
    var objFile = $(this)[0].files[0];
    // APPEND FILE TO POST DATA
    objFormData.append('userfile', objFile);
    $.ajax({
        url: 'Here Your Server-Url'
        type: 'POST',
        contentType: false,
        data: objFormData,
        //JQUERY CONVERT THE FILES ARRAYS INTO STRINGS.SO processData:false
        processData: false,
        success: function(data) {}
    });
});

答案 1 :(得分:1)

试试这个:

var data = new FormData(document.getElementById("yourFormID")); // your form ID
var url = jQuery("#yourFormID").attr("action"); // your form action 
$.ajax({
    url: url,
    type: "POST",
    data: data, // this will get all the input fields of your form.
    enctype: 'multipart/form-data',
    processData: false,  // tell jQuery not to process the data
    contentType: false,   // tell jQuery not to set contentType
    dataType: 'json', // as you want
    success: function(response) {        
        // success 
    }
});  // JQUERY Native Ajax End