我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上载吗?

$.ajax({
    type: "POST",
    timeout: 50000,
    url: url,
    data: dataString,
    success: function (data) {
        alert('success');
        return false;
    }
});

如果可能,我需要填写数据部分吗?这是正确的方式吗?我只将文件POST到服务器端。

我一直在搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。


当前回答

使用XMLHttpRequest()确实可以进行AJAX上载。无需iframes。可以显示上载进度。

有关详细信息,请参阅:答案https://stackoverflow.com/a/4943774/873282对jQuery Upload Progress和AJAX文件上传提出质疑。

其他回答

var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
    url: 'url',
    type: 'POST',
    data: dataform,
    async: false,
    success: function(res) {
        response data;
    },
    cache: false,
    contentType: false,
    processData: false
});

简单上载表单

<脚本>//表单提交$(“表单”).submit(函数(evt){evt.preventDefault();var formData=新的formData($(this)[0]);$.ajax美元({url:'fileUpload',类型:'POST',data:formData,异步:false,缓存:false,contentType:false,enctype:'多部分/表单数据',processData:false,成功:函数(响应){警报(响应);}});return false;});</script><!--上载表单--><表单><表><tr><td colspan=“2”>文件上载</td></tr><tr><th>选择文件</th><td><input id=“csv”name=“csv“type=“file”/></td></tr><tr><td colspan=“2”><input-type=“submit”value=“subject”/></td></tr></table></form>

这是我的代码

var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
 return false;
}
else {
 formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
  formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
 type: 'POST',
 data: formData,
 contentType: false,
 processData: false,
 cache: false,
 url: '/Controller/Action',
 success: function (response) {
 if (response.Success == true) {
    return true;
 }
 else {
    return false;
 }
 },
 error: function () {
   return false;
 },
 failure: function () {
   return false;
 }
 });

$(“#form id”).submit(函数(e){e.预防违约();});$(“#form id”).submit(函数(e){var formObj=$(此);var formURL=formObj.attr(“操作”);var formData=新的formData(this);$.ajax美元({url:formURL,类型:'POST',data:formData,processData:false,contentType:false,异步:true,缓存:false,enctype:“multipart/form data”,dataType:“json”,成功:函数(数据){if(data.success){警报(data.success)} if(data.error){警报(data.error)} }});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js“></script><form class=“form horizontal”id=“form id”action=“masterFileController”enctype=“multipart/form data”><button class=“btn success btn”type=“submit”id=“btn save”>提交</button></form>

servlet响应为“out.print(“您的响应”);”

通过ajax上传文件不再需要Iframes。我最近自己做过。查看以下页面:

使用AJAX和jQuery上传HTML5文件

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-界面

更新了答案并进行了清理。使用getSize函数检查大小或使用getType函数检查类型。添加了progressbar html和css代码。

var Upload = function (file) {
    this.file = file;
};

Upload.prototype.getType = function() {
    return this.file.type;
};
Upload.prototype.getSize = function() {
    return this.file.size;
};
Upload.prototype.getName = function() {
    return this.file.name;
};
Upload.prototype.doUpload = function () {
    var that = this;
    var formData = new FormData();

    // add assoc key values, this will be posts values
    formData.append("file", this.file, this.getName());
    formData.append("upload_file", true);

    $.ajax({
        type: "POST",
        url: "script",
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', that.progressHandling, false);
            }
            return myXhr;
        },
        success: function (data) {
            // your callback here
        },
        error: function (error) {
            // handle error
        },
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000
    });
};

Upload.prototype.progressHandling = function (event) {
    var percent = 0;
    var position = event.loaded || event.position;
    var total = event.total;
    var progress_bar_id = "#progress-wrp";
    if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
    }
    // update progressbars classes so it fits your code
    $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
    $(progress_bar_id + " .status").text(percent + "%");
};

如何使用Upload类

//Change id to your id
$("#ingredient_file").on("change", function (e) {
    var file = $(this)[0].files[0];
    var upload = new Upload(file);

    // maby check size or type here with upload.getSize() and upload.getType()

    // execute upload
    upload.doUpload();
});

Progressbar html代码

<div id="progress-wrp">
    <div class="progress-bar"></div>
    <div class="status">0%</div>
</div>

Progressbar css代码

#progress-wrp {
  border: 1px solid #0099CC;
  padding: 1px;
  position: relative;
  height: 30px;
  border-radius: 3px;
  margin: 10px;
  text-align: left;
  background: #fff;
  box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}

#progress-wrp .progress-bar {
  height: 100%;
  border-radius: 3px;
  background-color: #f39ac7;
  width: 0;
  box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}

#progress-wrp .status {
  top: 3px;
  left: 50%;
  position: absolute;
  display: inline-block;
  color: #000000;
}