简体   繁体   中英

C# - Send a file in the body of an http request using RestRequest

I tried sending an xlsx file (from path) in the body of a POST http request. I was able to send the file but it arrived as a corrupted file.(I have no way to try to check what's the issue on the api, because it's a api like Amazon etc.) this is the code I tried:

    public async Task<string> PostPostman()
        {
         try
            {
                string filePath = @"D:\example2.xlsx";

                FileStream fs = File.OpenRead(filePath);
                var streamContent = new StreamContent(fs);
                streamContent.Headers.Add("Content-Type", "application/xlsx");
                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", streamContent.ReadAsStringAsync().Result, ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }

I found the issue was that ReadAsStringAsync() opened the file but didn't close it.

The solution I found is to send the file with File.ReadAllBytes(filePath) which reads the file and closes it back.

This is the final code:

public async Task<string> PostPostman()//found the code from the postman request I sent
        {
            try
            {
                string filePath = @"D:\example2.xlsx";

                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", File.ReadAllBytes(filePath), ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM