How to set up a Web API controller for multipart/form-data

前端 未结 8 2115
萌比男神i
萌比男神i 2020-11-27 02:51

I am trying to figure this out. I was not getting any useful error messages with my code so I used something else to generate something. I have attached that code after the

相关标签:
8条回答
  • 2020-11-27 03:50

    check ur WebApiConfig and add this

    GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
    
    0 讨论(0)
  • 2020-11-27 03:57

    You can use something like this

    [HttpPost]
    public async Task<HttpResponseMessage> AddFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }
    
        string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
        var provider = new MultipartFormDataStreamProvider(root);
        var result = await Request.Content.ReadAsMultipartAsync(provider);
    
        foreach (var key in provider.FormData.AllKeys)
        {
            foreach (var val in provider.FormData.GetValues(key))
            {
                if (key == "companyName")
                {
                    var companyName = val;
                }
            }
        }
    
        // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
        // so this is how you can get the original file name
        var originalFileName = GetDeserializedFileName(result.FileData.First());
    
        var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
        string path = result.FileData.First().LocalFileName;
    
        //Do whatever you want to do with your file here
    
        return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
    }
    
    private string GetDeserializedFileName(MultipartFileData fileData)
    {
        var fileName = GetFileName(fileData);
        return JsonConvert.DeserializeObject(fileName).ToString();
    }
    
    public string GetFileName(MultipartFileData fileData)
    {
        return fileData.Headers.ContentDisposition.FileName;
    }
    
    0 讨论(0)
提交回复
热议问题