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

本文关键字:文件 数据 使用 REST | 更新日期: 2023-09-27 18:32:11

我有以下代码

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;
        }

当我执行此操作并上传文件时,我正在获取空文件数据. 其中文件上传是我的模型

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

还有其他方法可以做. 请帮助我

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

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);
            };