我正在调用API https://do.convertapi.com/Pdf2PowerPoint
他们的API详情网站是 https://www.convertapi.com/
要在C#文档中上传文件,他们使用了client.UploadFile()函数,该函数需要来自物理位置的文件名参数。在我的情况下,我有动态的PDF文件的字节,而不是存储到物理位置,我想上传该字节。我正在使用client.UploadData()函数,它需要字节数组,我已经提供了。但他们的API抛出错误,并要求提供必须的文件名。
我认为API的开发者只能回答。但是如果你们有任何想法,我是否在上传文件时犯了任何错误。请提出您的解决方法。
请按要求在下方找到我的代码
var client = new WebClient();
var data = new NameValueCollection();
data.Add("OutputFileName", "TestOutput.pptx"); //Optional
data.Add("File", "Revised.pdf");
data.Add("ApiKey", "484700111"); //API Key must be set if you purchased membership with credits. Please login to your control panel to find out your API Key http://www.convertapi.com/prices
try
{
client.QueryString.Add(data);
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
//I am using ReadAllBytes Approach for now as in my practical scenario I am going to get bytes instead of sending file from Physical location
byte[] Arr = File.ReadAllBytes(@"D:\PPTTest\Level I and II Revised.pdf");
// Error here : File Parameter can not be null
var response = client.UploadData("https://do.convertapi.com/Pdf2PowerPoint", Arr);
var responseHeaders = client.ResponseHeaders;
var path = Path.Combine(@"D:\PPTTest\", responseHeaders["OutputFileName"]);
File.WriteAllBytes(path, response);
//Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
}
catch (WebException e)
{
Console.WriteLine("Exception Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
谢谢, 希拉
答案 0 :(得分:1)
Code taken from this post。您必须上传包含multipart / form-data请求的文件,如下所示:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(username), "username");
form.Add(new StringContent(useremail), "email");
form.Add(new StringContent(password), "password");
form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("PostUrl", form);