使用MultipartFormDataStreamProvider和ReadAsMultipartAsync

时间:2012-12-05 21:26:44

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

我如何在MultipartFormDataStreamProvider中使用Request.Content.ReadAsMultipartAsyncApiController

我已经搜索了一些教程,但我无法使用它们中的任何一个,即使用.net 4.5。

这就是我目前得到的:

public class TestController : ApiController
{
    const string StoragePath = @"T:\WebApiTest";
    public async void Post()
    {
        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (MultipartFileData fileData in streamProvider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
            }
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }
    }
}

我得到了例外

  

MIME多部分流的意外结束。 MIME多部分消息不是   完整。

await task;运行时。 有没有人知道我做错了什么或者在使用web api的普通asp.net项目中有一个工作示例。

2 个答案:

答案 0 :(得分:31)

我解决了错误,我不明白这与多部分流的结束有什么关系,但这是工作代码:

public class TestController : ApiController
{
    const string StoragePath = @"T:\WebApiTest";
    public async Task<HttpResponseMessage> Post()
    {
        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));
            await Request.Content.ReadAsMultipartAsync(streamProvider);
            foreach (MultipartFileData fileData in streamProvider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(StoragePath, fileName));
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
        }
    }
}

答案 1 :(得分:7)

首先,您应该在ajax请求标头中将 enctype 定义为 multipart / form-data。

[Route("{bulkRequestId:int:min(1)}/Permissions")]
    [ResponseType(typeof(IEnumerable<Pair>))]
    public async Task<IHttpActionResult> PutCertificatesAsync(int bulkRequestId)
    {
        if (Request.Content.IsMimeMultipartContent("form-data"))
        {
            string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");

            var streamProvider = new MyStreamProvider(uploadPath);

            await Request.Content.ReadAsMultipartAsync(streamProvider);

            List<Pair> messages = new List<Pair>();
            foreach (var file in streamProvider.FileData)
            {
                FileInfo fi = new FileInfo(file.LocalFileName);
                messages.Add(new Pair(fi.FullName, Guid.NewGuid()));
            }

            //if (_biz.SetCertificates(bulkRequestId, fileNames))
            //{
            return Ok(messages);
            //}
            //return NotFound();
        }
        return BadRequest();
    }
}




public class MyStreamProvider : MultipartFormDataStreamProvider
{
    public MyStreamProvider(string uploadPath) : base(uploadPath)
    {
    }
    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        string fileName = Guid.NewGuid().ToString()
            + Path.GetExtension(headers.ContentDisposition.FileName.Replace("\"", string.Empty));
        return fileName;
    }
}