3

I am trying to upload a file in asp.net core web api. For that i have one web app which is calling my web api.

Here is the web app code in which i am attaching the file

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Sample");

    using (var content = new MultipartFormDataContent())
    {
        var fileContent2 = new StreamContent(firmwareImage.InputStream);
        fileContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = firmwareImage.FileName
        };
        content.Add(fileContent2);

        var result = await client.PostAsync(serviceUrl, content);
        var response = await result.Content.ReadAsStringAsync();
    }
}

and here is the screenshot of that attched content while debugging. Sorry for the blurry image in debug value portion.

enter image description here

now in web api i am receiving this request by

 var files = Request.Form.Files;

but i am getting empty files always. Count is always zero. Here is the screenshot of same request. enter image description here

what i am doing wrong and why i am not getting attached file in web api?

2
  • 5
    Have you tried setting the content type header as multipart/form-data? Commented Aug 31, 2017 at 12:30
  • yes but that code was not able to work for me. so i have changed the api request code with multipart/form-data. Thanks. Commented Sep 1, 2017 at 12:56

2 Answers 2

2

I was not able to post an image from above code so i have tried below code and it works fine.

 HttpClient httpClient = new HttpClient();
 MultipartFormDataContent form = new MultipartFormDataContent();

 FileStream fs = System.IO.File.OpenRead("your file path");
 var streamContent = new StreamContent(fs);

 var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
 imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

 form.Add(imageContent, "image", Path.GetFileName("your file name"));
 var response = httpClient.PostAsync("apiurl", form).Result;
Sign up to request clarification or add additional context in comments.

Comments

1

I think you are missing enctype = "multipart/form-data". you need this on your mvc form

@using (Html.BeginForm("action", "controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                    <input name="file" type="file" multiple />
                    <button type="submit" >  
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.