使用POST Web请求发送PDF base64

时间:2020-10-22 16:55:53

标签: api xamarin post http-post webrequest

我有一个任务,我需要将转换为base64字符串的pdf上传到Http帖子。我之前使用改装进行过尝试,但未能上传。现在,我正在尝试一种不同的方法。

我使用了Web请求POST方法,首先将PDF转换为base64,但是在我称为stream.write方法的那一部分,由于文件已经转换为base64字符串和流,因此出现了错误。写参数是字节数组。

另外,如何使用Web请求将这些添加到正文中?

“ mime”:“ application / pdf”,

“数据”:“ base64-data =“

 string pdfBase64;

 const string pdfFileName = "file.pdf";
    
                    using (var pdfStream = await FileSystem.OpenAppPackageFileAsync(pdfFileName))
                    {
                        using (var pdfReader = new StreamReader(pdfStream))
                        {
                            var fileContents = await pdfReader.ReadToEndAsync();
                            pdfBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(fileContents));
                        }
                    }
    
                    WebRequest request = WebRequest.Create("https://goodmorning-axa-dev.azure-api.net/upload");
                    request.Method = "POST";
                    request.ContentLength = pdfBase64.Length;
                    request.ContentType = "application/json";             
                    request.Headers.Add("x-axa-api-key", apiKey);
    
                    Stream stream = request.GetRequestStream();
                    stream.Write(pdfBase64, 0, pdfBase64.Length);
                    stream.Close();
    
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    stream = response.GetResponseStream();
    
                    StreamReader sr = new StreamReader(stream);
                    Toast.MakeText(this, sr.ReadToEnd(), ToastLength.Short).Show();
                    
                    sr.Close();
                    stream.Close();

0 个答案:

没有答案