Hack Forums
[C#] How can I send a file in an api using httpclient in net core? - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] How can I send a file in an api using httpclient in net core? (/showthread.php?tid=6097464)



How can I send a file in an api using httpclient in net core? - Nemo2478 - Jul 24, 2020

Hello everybody,

I am receiving an object that contains the properties of a file as well as the content. The content property I have it declared as string to store the content of the file. So I already have the method in my api to receive the object, however I need to send these parameters via post using a uri that points to another api. But I am somewhat confused, because I don't know exactly how I should do it and if I have to convert the content of my file before. I leave the code I have so far:

Code
[Route("[controller]/pu/SendArchive")]
        [SwaggerOperation("SendArchive")]
        public async Task SendArchive([FromBody] Archive archive, string request)
        {
            var username = "";
            var password = "";
            var name = "Job";

            var authInfo = username + ":" + password;
            var encoded = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            var requestURL = "http://cobpm01p.mar.net/rest/bp/wle/v1/process/" + request +
                                         "?action=addDocument&name=" + name + "&docType=file&data=data";

            var postParameters = new Dictionary<string, object>();
            postParameters.Add("data", new FormUpload.FileParameter(archive.content, archive.fileName, archive.mimeType));
            //string userAgent = null;
            var webResponse = FormUpload.MultipartFormPost(Uri.EscapeUriString(requestURL), userAgent,
                postParameters,
                "Authorization", "Basic " + encoded);
            // Process response  
            var responseReader = new StreamReader(webResponse.GetResponseStream());
            var returnResponseText = responseReader.ReadToEnd();
            webResponse.Close();
            var results = JsonConvert.DeserializeObject<dynamic>(returnResponseText);
            if (results.status == "200") {
            }
                
        }


Regards and thanks


RE: How can I send a file in an api using httpclient in net core? - Sonimnx - Aug 6, 2020

I think you should convert the file to binary.

Check here https technowide.net/2012/09/01/upload-binary-data-http-post/