Custom form data with multiple files to Web API controller

邮差的信 提交于 2019-11-30 23:52:04

I used this along with angular and it worked fine for me:

public partial class UploadController : ApiController
{
    [HttpPost]
    public Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent()) {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

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

        // Read the form data and return an async task.
        var task = Request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(t =>
            {
                if (t.IsFaulted || t.IsCanceled) {
                    Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                }


                foreach (MultipartFileData file in provider.FileData) {
                    using (StreamReader fileStream = new StreamReader(file.LocalFileName)){
                        if (provider.FormData.AllKeys.AsParallel().Contains("demo")){
                            //read demo key value from form data successfully
                        }
                        else{
                           //failed to read demo key value from form.
                        }
                    }
                }
                return Request.CreateResponse(HttpStatusCode.OK, "OK");
            });

        return task;
    }
...

I've created a MediaTypeFormatter that decodes the multipart/form-data and provides a HttpPostedFileBase via model binding. It makes file uploads as easy as any other API parameters. It currently loads the full file upload into the memory but the formatter can be easily adjusted to also write the uploaded data into a temporary upload directory.

https://gist.github.com/Danielku15/bfc568a19b9e58fd9e80

Simply register the formatter in your API configuration and you're all set to use it in your data transfer models:

Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!