AJAX 和文件上传

AJAX and file upload

我已经进行了大量谷歌搜索以到达我所在的位置,但最后一点似乎让我望而却步。有人知道为什么 reader.result 数据是空白的吗?我玩过不同的场景,有时 ajax post 不包括 reader.result (该代码不在此处,因为我已经继续)。我想一旦我得到实际的 reader.result 就可以将其字符串化,以便在 reader.onload 函数的范围之外传递给我自己的变量。

<form id="UploadForm"><input id="FileUpload" type="file"></form>

$('#FileUpload').on("change",function(e) {
var data = {};
var StepID = $(this).data("StepID");
var Step = $(".InstructionPhotos[data-id=" + StepID + "]");
var reader = new FileReader();
var s;

reader.onload = function (e) {
        $("<img class='image uploading' src='" + e.target.result + "'>").appendTo($("#Slides"));
        s = e.target.result;

}
reader.readAsDataURL(e.target.files[0]);

console.log( reader.result ); //This is blank
console.log (s); //This is undefined

data['RecipeID'] = RecipeID;
data['File'] = $(".uploading").attr("src");
data['Filename'] = e.target.files[0].name;
data['StepID' ] = $(this).data("StepID");
data['page'] = 'recipe_editor';
data['ajax'] = true;

$.ajax({
     type: "POST",
     url: "index.php",
     data: data,
     dataType: "json"
});
});

来自the MDN documentation

This property is only valid after the read operation is complete,

您在致电 readAsDataURL 后立即阅读它。您不是在等待 load 事件触发。