ASP .Net Web API RC:Multipart文件上传到Memorystream

时间:2012-08-30 11:39:28

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

我正在尝试将(a)上传的文件保存到数据库/内存流中,但我无法弄明白。

我现在所拥有的只是:

public Task<HttpResponseMessage> AnswerQuestion()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    var root = HttpContext.Current.Server.MapPath("~/App_Data");
    var provider = new MultipartFormDataStreamProvider(root);

    var task = Request.Content.ReadAsMultipartAsync(provider).
        ContinueWith<HttpResponseMessage>(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
            {
                Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
            }

            foreach (var file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        });

    return task;
}

但当然这只会将文件保存到特定位置。我想我必须使用从MediaTypeFormatter派生的自定义类来将其保存到MemoryStream,但我不知道如何去做。

请帮忙。提前谢谢!

2 个答案:

答案 0 :(得分:27)

可以将多部分内容读入抽象MultipartStreamProvider类的任何具体实现中 - 请参阅http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/8fda60945d49#src%2fSystem.Net.Http.Formatting%2fMultipartStreamProvider.cs

这些是:

- MultipartMemoryStreamProvider 
- MultipartFileStreamProvider 
- MultipartFormDataStreamProvider 
- MultipartRelatedStreamProvider

在你的情况下:

if (Request.Content.IsMimeMultipartContent())
{              
   var streamProvider = new MultipartMemoryStreamProvider();
   var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
   {
       foreach (var item in streamProvider.Contents)
       {
           //do something
       }
   });
}

答案 1 :(得分:3)

您可以为您的方案使用 MultipartMemoryStreamProvider

[已更新]注意到您正在使用RC,我认为MultipartMemoryStreamProvider是在RC后添加的,目前处于RTM状态。