从 Angular 客户端传递的 Excel 个文件中的 Serialization/De-serialization 个将由 WCF 存储在目录中

Serialization/De-serialization of Excel file being passed from Angular client to be stored in directory by WCF

我有一个要求,我必须将文件从客户端上传到服务器。方式代码结构如下

1) Angular编码的客户端。请参阅下面的控制器代码

function controller($scope, $http, $upload, AppModel, WebFunctionService) {

        $scope.UploadCFTCFiles = function (evt) {


            var client = new XMLHttpRequest();

            var files = document.getElementById('updCftcFileUploader').files;
            for (var i = 0; i < files.length; i++) {
                var formData = new FormData();
                var file = files[i];
                if (file) {
                    alert("Name: " + file.name + "\n" + "Last Modified Date :" + file.lastModifiedDate);
                    formData.append("CftcUploads", file);
                    client.open("post", "/Apps/DTCC/UploadCftcFiles", true);
                    client.setRequestHeader("Content-Type", "multipart/form-data");
                    client.send(formData);  /* Send to server */
                }
            }
}

2) 从客户端接收文件的后端服务器端代码将其序列化并将其发送到 WCF 服务。

[Route("UploadCFTCFiles")]
    [HttpPost]
    public void UploadCftcFiles(HttpRequestMessage request)
    {
        Stream stream = new MemoryStream();
        var buffer = request.Content.ReadAsByteArrayAsync().Result;
        stream.Write(buffer, 0, buffer.Length);
        _client.UploadCftcFiles(stream);
    }  

不确定我的做法是否正确。但是我可以在服务器端看到请求 header 并且数据确实可以过来。 “_client”引用是 WCF 服务的实例。

3) 接收文件流的 WCF 服务,将其反序列化并将其保存在给定目录中

public bool UploadCftcFiles(Stream stream)
    {
        // upload the file to "//uscserver/cftcdata/datadumps here"
        return false;
    }

我已经设法完成了将文件从客户端 Angular 代码传递到服务器端代码的第一步。有点卡在第 2 步。任何人都可以帮忙。应用整体架构如下

您在代码中使用了 ReadAsByteArrayAsync。不能保证方法完成时会完整读取内容。您需要等待任务完成。试试这个:

[Route("UploadCFTCFiles")]
    [HttpPost]
    public void UploadCftcFiles(HttpRequestMessage request)
    {
        Stream stream = new MemoryStream();
        var task = request.Content.ReadAsByteArrayAsync();
        task.Wait();
        var buffer = task.Result;
        stream.Write(buffer, 0, buffer.Length);
        _client.UploadCftcFiles(stream);
    }

解释见下文link: