Upload file via POST to Webapi

Asked

Viewed 6,264 times

6

I need to upload a file to a WebAPI, I am using the following code to upload

public void Enviar()
{   
    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 Webapi I have the following 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);
    }

When I run, I’m always getting

HttpStatusCode.UnsupportedMediaType

  • Only works with Webrequest?

  • 1

    The idea would be with Webrequest, but if you have another code, I am open-minded rsrs

  • good posted... !!! with Webrequest did not work with me. If you can also change the title of your question!

1 answer

8


With Httpclient, saving a text file to a Controller WebApi:

Sending:

[HttpGet]
public void Enviar()
{
    string fileName = Server.MapPath("~") + "/Files/arq.txt";

    using (HttpClient client = new HttpClient())
    using (MultipartFormDataContent content = new MultipartFormDataContent())
    using (FileStream fileStream = System.IO.File.OpenRead(fileName))
    using (StreamContent fileContent = new StreamContent(fileStream))
    {

        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/plain");
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            FileName = "arq.txt",                   
        };
        fileContent.Headers.Add("name", "arq.txt");
        content.Add(fileContent);
        var result = client.PostAsync("http://localhost:62951/api/arquivo", content).Result;
        result.EnsureSuccessStatusCode();
    }
}

Receiving:

public Task<HttpResponseMessage> Post()
{
    HttpRequestMessage request = Request;

    if (!request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }
    string root = System.Web.HttpContext.Current.Server.MapPath("~/Data/");
    MultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(root);            
    var task = request.Content.ReadAsMultipartAsync(provider);            
    return task.ContinueWith(o =>
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("File uploaded.")
            };
        }
    );
}

To save the file with the given name implements the class:

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) 
        : base(path) { }
    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName;
    }
}
  • excellent approach Virgilio, just not captured how do I save the file

  • Cool you ask, note the variable root is the folder of the site that is saved the file "Arq.txt".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.