Search code examples
c#jsonhttpwebrequest

Send Json as body and file webrequest


How to send both body and also a file?

From the API Guide: "Upload Requests are submitted with multiple parts: body (request) and file buffer (file)."

I know how to send only a Json as body, but I need now to seng Json as body and also a file.

My code looks something like:

            const string WEBSERVICE_URL = "https://myurl.com";
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data;boundary=12345678912345678912345678";
            webRequest.Headers.Add("Authorization:7786FFFGFDDDP");

And:

      string json="{"\some json"\ :\"here\" }"
        using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
        {

            streamWriter.Write(json);             
        }

        var httpResponse = (HttpWebResponse)webRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            Console.WriteLine(result.ToString());
        }

But how to send both file and body together? I mean I want also to upload some file wih path @c:\\myFile.txt


Solution

  • I need to do this in a Xamarin application. Post an image to a web api with token based authentication. I made some changes in code to be posible use in a web application.

    public async void SendFile()
    {
        using (System.IO.FileStream stream = System.IO.File.Open(@"c:\file.txt", System.IO.FileMode.Open))
        {
            var content = new System.Net.Http.MultipartFormDataContent();
            content.Add(new System.Net.Http.StreamContent(stream),
                    "\"file\"",
                    "Path to your file (ex: c:\temp\file.txt");
    
            await PostItemAsyncWithToken("url to post", content, "accessToken");
        }
    }
    
    public async System.Threading.Tasks.Task<bool> PostItemAsyncWithToken(string url, System.Net.Http.HttpContent content, string accessToken)
    {
        try
        {
            using (var httpClient = new System.Net.Http.HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
                System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(url, content).ConfigureAwait(false);
    
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        catch (System.Exception ex)
        {
            throw new System.Exception("Error message", ex);
        }
    }