如何使用 Web API 与 viewModel 一起发送文件或如何使用临时数据保存

How to send files along with the viewModel using Web API or how to save using temporary data

我已经阅读了很多有类似问题的 Whosebug 帖子以及一些博客,但我仍然不确定如何解决我的问题:(

我有 angularJS 指令允许将文件上传到服务器。代码是这样的:

[HttpPost]       
    [Route("UploadFile")]
    public async Task<HttpResponseMessage> UploadFile()
    {          
        // Check if the request contains multipart/form-data.
        if (Request.Content.IsMimeMultipartContent("form-data"))
        {               
            try
            {
                var resultOut = new List<FileUploadResult>();

                var streamProvider = new MultipartMemoryStreamProvider();
                streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

                foreach (
                    var item in
                    streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName))
                )
                {
                    FileUploadResult file = new FileUploadResult()
                    {
                        FileName = item.Headers.ContentDisposition.FileName,
                        //   Content = fileBytes, // No need to pass the info back as we're not going to read it save it yet
                        Key = Guid.NewGuid().ToString(),
                        Type = item.Headers.ContentDisposition.DispositionType
                    };
                    resultOut.Add(file);
                    //using (Stream stFileSource = new MemoryStream(await item.ReadAsByteArrayAsync()))                     {
                    //    byte[] fileBytes;

                    //    fileBytes = new Byte[stFileSource.Length];
                    //    stFileSource.Read(fileBytes, 0, Convert.ToInt32(stFileSource.Length));
                    //    FileUploadResult file = new FileUploadResult()
                    //    {
                    //        FileName = item.Headers.ContentDisposition.FileName,
                    //     //   Content = fileBytes, // No need to pass the info back as we're not going to read it save it yet
                    //        Key = Guid.NewGuid().ToString(),
                    //        Type = item.Headers.ContentDisposition.DispositionType
                    //    };
                    //    resultOut.Add(file);                            
                    //}
                }
                return Request.CreateResponse(HttpStatusCode.OK, resultOut.ToArray());
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

Also 指令将 Files 数组保存到 属性。我的用户表单允许删除一些文件/添加更多文件,然后我想将表单(有点复杂的视图模型)中的信息与文件一起保存。到目前为止,我无法弄清楚这个问题。我在这里看到的一种可能性是使用 Repository 将 UploadFile 方法中的文件保存到数据库中。但是,我宁愿将其保存到一些临时的 table 中(例如 #FileInfo table),而不是实际的 table。或者也许有一种方法可以将文件(及其二进制内容)保存到某个内存对象中,以便在我准备好保存模型数据时能够取回该内容?您能否展示临时存储库存储的实现或为我的困境提供一些其他想法?

首先,您的指令需要使用 'multipart/form-data' 创建一个 post 请求。

检查 this link 以供参考。

但是,我们使用 angular file upload 来做到这一点。

angular
.module('app', ['angularFileUpload'])
.controller('AppController', function($scope, FileUploader) {
    $scope.uploader = new FileUploader(
    {
        url: 'Your/upload/url',
        headers: {
            'autorization': 'Bearer token if you need it'
        },
        onProgressItem: function () {
             ...
        },
        onSuccessItem: function (opt, data) {
            ...
        },
        onErrorItem: function (opt) {
            ...
        }
    });

    //you may want to wrap the following in an event
    var uploadItem = $scope.uploader.queue[uploader.queue.length - 1];
    uploadItem.formData.push({
                someData: "someData",
                moreData: "moreData"
            });

    uploadItem.upload();
    uploadItem.formData = [];

});

然后在您的控制器中,您可以执行以下操作来检索您需要的内容:

//your request
var request = HttpContext.Current.Request;

//your fields
var someData = request.Form["someData"];
var moreData = request.Form["moreData"];

//your file
var file = request.Files["file"];

看起来像是 TempData 的工作:

TempData in ASP.NET MVC is basically a dictionary object derived from TempDataDictionary. TempData stays for a subsequent HTTP Request as opposed to other options (ViewBag and ViewData) those stay only for current request. So, TempdData can be used to maintain data between controller actions as well as redirects.

示例:

 //Controller Action 1 (TemporaryEmployee)
 public ActionResult TemporaryEmployee()
{
                Employee employee = new Employee
                {
                        EmpID = "121",
                        EmpFirstName = "Imran",
                        EmpLastName = "Ghani"
                };
                TempData["Employee"] = employee;
                return RedirectToAction("PermanentEmployee");
}

 //Controller Action 2(PermanentEmployee)
 public ActionResult PermanentEmployee()
{
               Employee employee = TempData["Employee"] as Employee;
               return View(employee);
 }