如何将MultipartMemoryStreamProvider的文件内容作为字节数组获取?

时间:2013-10-31 15:38:13

标签: c# .net file-upload asp.net-web-api

我创建了一个使用FormData将文件上传到Web API控制器的组件。

如何将MultipartMemoryStreamProvider中的文件内容作为字节数组获取?

这是Web Api方法

   public Task<IEnumerable<FileModel>> Post()
   {             
     if (Request.Content.IsMimeMultipartContent())
        {            
            var streamProvider = new MultipartMemoryStreamProvider();
            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileModel>>(t =>
            {

                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                FileDataBO filedata;
                var fileInfo = streamProvider.Contents.Select(i => {
                    //save to db
                    filedata = new FileDataBO ();
                    filedata.FileName = i.Headers.ContentDisposition.FileName;
                    filedata.FileType = "jpeg";

                    // HOW TO GET FILE CONTENT HERE??? IT SHOULD BYTE[]
                    //filedata.FileContent = ???

                    //TODO
                    //_fileDataService.SaveFile(filedata);    

                    return new FileModel(i.Headers.ContentDisposition.FileName, 2048);
                });
                return fileInfo;
            });

            return task;
        }             
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }       
   }

1 个答案:

答案 0 :(得分:6)

您应该可以通过i.ReadAsByteArrayAsync()

获取内容