post image to asp.net API 2 and angular 2

后端 未结 1 1780
自闭症患者
自闭症患者 2021-01-25 20:30

i get 415 (Unsupported Media Type) when i try to post image to ASP.Net API 2 The request entity\'s media type \'multipart/form-data\' is not supported for this

相关标签:
1条回答
  • 2021-01-25 20:57

    You should use a custom MediaTypeFormatter. More information here: http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters and a sample here http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html#.V5MDDzV7qYg

        public class CustomFormatter : MediaTypeFormatter
        {
            public CustomFormatter()
            {
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
            }
    
            public override bool CanReadType(Type type)
            {
                return type == typeof(Attachment);
            }
    
            public override bool CanWriteType(Type type)
            {
                return false;
            }
    
            public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
            {
                var provider = await content.ReadAsMultipartAsync();
    
                var modelContent = provider.Contents
                    .FirstOrDefault(c => c.Headers.ContentType.MediaType == "application/json"); // Can also use ContentDisposition.Name.Normalize == "attachment"
    
                var attachment = await modelContent.ReadAsAsync<Attachment>();
    
                var fileContents = provider.Contents
                    .Where(c => c.Headers.ContentType.MediaType == "image/jpeg").FirstOrDefault(); // can also use ContentDisposition.Name.Normalize() == "image"
    
                attachment.Content = await fileContents.ReadAsByteArrayAsync();
    
                return attachment;
    
            }
        }
    

    Register the custom media formatter:

    private void ConfigureWebApi(HttpConfiguration config)
    {
        //other code here
        config.Formatters.Add(new CustomFormatter());
    }   
    

    A post will like below

    POST http://localhost/api/FileUpload HTTP/1.1
    Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468
    User-Agent: Fiddler
    Content-Length: 88778
    
    ---------------------------acebdf13572468
    Content-Type: application/json; charset=utf-8
    Content-Disposition: form-data; name=attachment
    
    {"ListingId":"testl"}
    ---------------------------acebdf13572468
    Content-Disposition: form-data; name=image; filename=image.jpg
    Content-Type: image/jpeg
    
    Image content
    ---------------------------acebdf13572468--
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题