Solved

UPLOAD FILE TO Web API USING POST

Posted on 2016-09-16
5
84 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 24

Expert Comment

by:dgrafx
Comment Utility
You could use plupload
http://www.plupload.com/
0
 

Author Comment

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

Expert Comment

by:dgrafx
Comment Utility
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
Comment Utility
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
Comment Utility
Very good. It worked fine!!!
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Periodically we have to update or add SSL certificates for customers. Depending upon your hosting plan you may be responsible for the installation and/or key generation. In the wake of Heartbleed many sites were forced to re-key. We will concen…
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…
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…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now