使用REST上传文件中的文件数据为null

我有以下代码

self.upload = function (file) { var path = $('#fileUpload').val(); var fr= new FileReader(); var ID = JSON.stringify({ ID:23, Name: file.name, Type: file.type, Size: file.size, Path: path, data:fr.readAsDataURL(file), }); $.ajax({ cache: false, url: "http://localhost:49589/api/files", type: "POST", dataType: "json", data: ID, contentType: "application/json; charset=utf-8", processData: false, success: function (json) { alert("Data Returned: " + JSON.stringify(json)); }, error: function (json) { alert("error" + JSON.stringify(json)); } }); 

即时执行文件上传。 我的控制器是

 [HttpPost] public string upload(filesUpload f) { byte[] jj = f.data; // **getting null here** string givenId = f.Path; return givenId; } 

当我执行此操作并上传文件即时获取空文件数据。 其中filesUpload是我的模型

我的代码出了什么问题。 我使用Knockout.js为viwe和drundal SPA框架

还有其他办法吗? 请帮助我

FileReader.readAsDataURL异步读取文件并且不返回任何内容。 您应该首先开始读取文件,然后捕获fr.onload事件,并从此处创建您的json对象并调用ajax。

upd:代码如下所示:

  self.upload = function (file) { var path = $('#fileUpload').val(); var fr= new FileReader(); fr.onload = function (frEvent) { var ID = JSON.stringify({ ID:23, Name: file.name, Type: file.type, Size: file.size, Path: path, data:frEvent.target.result, }); $.ajax({ cache: false, url: "http://localhost:49589/api/files", type: "POST", dataType: "json", data: ID, contentType: "application/json; charset=utf-8", processData: false, success: function (json) { alert("Data Returned: " + JSON.stringify(json)); }, error: function (json) { alert("error" + JSON.stringify(json)); } }); }; fr.readAsDataURL(file); };