2

I am trying to write code to upload file(s) by WinForm app to WebApi.

The WebApi code is like:

[HttpPost]
[Route("UploadEnvelope")]
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
public Task<HttpResponseMessage> PostUploadEnvelope()
{
    HttpRequestMessage request = this.Request;
    if (!request.Content.IsMimeMultipartContent())
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
    var provider = new MultipartFormDataStreamProvider(root);

    var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(o =>
        {
            foreach (MultipartFileData fileData in provider.FileData)
            {
                if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
                {
                    return Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted");
                }
                string fileName = fileData.Headers.ContentDisposition.FileName;
                if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
                {
                    fileName = fileName.Trim('"');
                }
                if (fileName.Contains(@"/") || fileName.Contains(@"\"))
                {
                    fileName = Path.GetFileName(fileName);
                }
                File.Move(fileData.LocalFileName, Path.Combine(root, fileName));
            }

            return new HttpResponseMessage()
            {
                Content = new StringContent("Files uploaded.")
            };
        }
    );
    return task;
}

But I am not sure how to call it and pass file in a client app.

static string UploadEnvelope(string filePath, string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);


        // How to pass file here ??? 

        var response = client.GetAsync(url + "/api/Envelope/UploadEnvelope").Result;

        return response.Content.ReadAsStringAsync().Result;
    }
}

Any help or suggestion is welcome. Thanks in advance!

1 Answer 1

2

First you are using Get method which is used for reading. You have to use Post instead.

Try the following:

public static string UploadEnvelope(string  filePath,string token, string url)
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        using (var content = new MultipartFormDataContent("Envelope" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
        {
            content.Add(new StreamContent(new MemoryStream(File.ReadAllBytes(filePath))), "filename", "filename.ext");
            using (var message = await client.PostAsync(url + "/api/Envelope/UploadEnvelope", content))
            {
                var input = await message.Content.ReadAsStringAsync();
                return "success";
            }
        }
    }
}

Note: For a large file you have to change configuration on IIS web.config.

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer! God bless you!

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.