20

我将如何在 a 中使用MultipartFormDataStreamProviderand ?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 项目中有一个工作示例。

4

2 回答 2

36

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

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");
        }
    }
}
于 2012-12-05T23:10:41.130 回答
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;
    }
}
于 2014-07-01T11:46:03.917 回答