Solved

UPLOAD FILE TO Web API USING POST

Posted on 2016-09-16
5
131 Views
Last Modified: 2016-09-19
I need to upload a file to a WebAPI, I'm using this code to do the upload

public void SendFilePost()
{  
    WebRequest request = WebRequest.Create(url);
    request.Method = "POST";
    byte[] byteArray = File.ReadAllBytes(fileName);
    request.ContentType = "multipart/form-data";
    request.ContentLength = byteArray.Length;

    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();
    WebResponse response = request.GetResponse();
    Console.WriteLine(((HttpWebResponse)response).StatusDescription);
    reader.Close();
    dataStream.Close();
    response.Close();
}
 In the WebAPI I have this code:

public async Task<HttpResponseMessage> Post()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
            return new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var streamProvider =
            new MultipartFormDataStreamProvider(".");

        await Request.Content.ReadAsMultipartAsync(streamProvider);

        var fileNames = streamProvider.BodyPartFileNames;

        foreach (var fileName in fileNames.Keys)
            Console.WriteLine(fileName + " --> " + fileNames[fileName]);

        return new HttpResponseMessage(HttpStatusCode.Created);
    }

I'm always receiving this code:

HttpStatusCode.UnsupportedMediaType
0
Comment
Question by:Anderson Meneses
  • 2
  • 2
5 Comments
 
LVL 25

Expert Comment

by:dgrafx
ID: 41802526
You could use plupload
http://www.plupload.com/
0
 

Author Comment

by:Anderson Meneses
ID: 41802932
It's a good plugin, I will use it in my web projects, but this project is Winforms.
0
 
LVL 25

Expert Comment

by:dgrafx
ID: 41803040
I see ...

I'm not aware that you can't use plupload with winforms
0
 
LVL 29

Accepted Solution

by:
Gautham Janardhan earned 500 total points
ID: 41805154
try this to post

public static async void SendFilePost(string url, string fileName)
        {
            using (var client = new HttpClient())
            using (var content = new MultipartFormDataContent())
            {
                client.BaseAddress = new Uri(url);
                var fileContent1 = new ByteArrayContent(File.ReadAllBytes(fileName));
                fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = "mydata.txt"
                };
                content.Add(fileContent1, "mydata.txt");

// make sure to change this to ur api 

                var result = client.PostAsync("/api/home", content).Result;

                Console.WriteLine(result.StatusCode);
                Console.ReadLine();
            }
        }

Open in new window

1
 

Author Closing Comment

by:Anderson Meneses
ID: 41805319
Very good. It worked fine!!!
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question