Search code examples
c#.netmultipartform-data

Httpclient multipart/form-data pust image


I am trying to send a Put request with binary file to upload to the server, using Httpclient.SendAsync or Httpclient.PutAsync. But all i got is 400 bad request in server response. Here is the code

private static HttpResponseMessage Upload()
    {
        var apiUri = string.Format(url);
        string url = (url);

        var message = new HttpRequestMessage();
        message.RequestUri = new Uri(apiUri);
        message.Method = HttpMethod.Put;

        var fileObj = Images.ChooseImageAndToInfoObject();

        using (var client = new HttpClient())
        using (var content = new MultipartFormDataContent())
        {
            var filestream = new FileStream(fileObj.filePath, FileMode.Open);

            content.Add(new StreamContent(filestream), fileObj.fileName, fileObj.fileNameWithExtension);
            content.Add(new StringContent("file"), "withName");
            content.Add(new StringContent("string"), "fileName");
            content.Add(new StringContent("image/*"), "mimeType");

            message.Content = content;

            message.Headers.Add("Authorization", MyToken);


            // var res = client.SendAsync(message).Result;
             var response = client.PutAsync(url, content).Result;
            return response;
        }

Hope for you, guys


Solution

  • Is it necessary to send the filename and mimetype via multipart-formdata? If not try to send the data as StreamContent and set the filename and mime type via the content header:

    private static HttpResponseMessage Upload()
        {
            var apiUri = string.Format(url);
            string url = (url);
    
            var message = new HttpRequestMessage();
            message.RequestUri = new Uri(apiUri);
            message.Method = HttpMethod.Put;
    
            var fileObj = Images.ChooseImageAndToInfoObject();
    
            using (var client = new HttpClient())
    
            var filestream = new FileStream(fileObj.filePath, FileMode.Open);
    
            var content = new StreamContent(filestream);
            content.Headers.ContentType = new MediaTypeHeaderValue(MimeMapping.GetMimeMapping(fileObj.filePath));
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") 
            { 
                Name = "\"files\"", 
                FileName = "\"" + fileName + "\""
            };
    
            message.Content = content;
    
            message.Headers.Add("Authorization", MyToken);
    
    
            // var res = client.SendAsync(message).Result;
            var response = client.PutAsync(url, content).Result;
            return response;
    

    Send the content via PUT if you set the file to a specific id or via Post:

    var response = client.PostAsync(url, content).Result;