【问题标题】:Using convertapi in Windows Store App在 Windows 应用商店应用程序中使用 convertapi
【发布时间】:2014-12-16 19:58:39
【问题描述】:

我在 Windows 商店应用程序项目中尝试Convertapi,我想发送一个 .docx 文件并获得一个 pdf 文件作为回报,我正在尝试发布一个帖子,但我不确定它是如何完成的,这是到目前为止我有什么,但它不起作用。

    private async Task GeneratePdfContract(string path) {
try {
    var data = new List < KeyValuePair < string, string >> {
            new KeyValuePair < string, string > ("Api", "5"),
                new KeyValuePair < string, string > ("ApiKey", "419595049"),
                new KeyValuePair < string, string > ("File", "" + stream2),

        };

    await PostKeyValueData(data);

} catch (Exception e) {

    Debug.WriteLine(e.Message);
}

}

private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();

}

我应该如何发送一个 .docx 文件并获得一个 .pdf 文件作为回报?

编辑:

private async Task GeneratePdfContract(string path)
    {
        try
        {
            using (var client = new System.Net.Http.HttpClient())
            {
                using (var multipartFormDataContent = new MultipartFormDataContent())
                {
                    var values = new[]
        {
            new KeyValuePair<string, string>("ApiKey", "413595149")
        };

                    foreach (var keyValuePair in values)
                    {
                        multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
                    }

                    StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);

                    StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");

                    byte[] fileBytes = await outputFile.ToBytes();


                    //multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(@"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');

                    multipartFormDataContent.Add(new ByteArrayContent(fileBytes));

                    const string requestUri = "http://do.convertapi.com/word2pdf";

                    var response = await client.PostAsync(requestUri, multipartFormDataContent);
                    if (response.IsSuccessStatusCode)
                    {
                        var responseHeaders = response.Headers;
                        var paths = responseHeaders.GetValues("OutputFileName").First();
                        var path2 = Path.Combine(@"C:\", paths);



                        StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
                        await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());


                    }
                    else
                    {
                        Debug.WriteLine("Status Code : {0}", response.StatusCode);
                        Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
                    }

                }
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine(e.Message);
        }

    }

@Tomas 试图稍微调整您的答案,因为 Windows 商店应用程序上似乎没有“File.ReadAllBytes”,我得到了这个回复:\

【问题讨论】:

  • 我认为您需要使用MultipartFormDataContent 而不是FormUrlEncodedContent。查看herehere 的示例。对于文件内容(基于我对该页面请求的摆弄),Content-Disposition 需要为form-data; name-"File"; filename="&lt;filename&gt;"(替换 )。 Content-Type may 必须是 application/msword,不确定。

标签: c# post windows-runtime windows-store-apps convertapi


【解决方案1】:

您不能将文件流作为字符串传递给 HttpClient。只需使用同样支持异步上传的 WebClient.UploadFile 方法。

using (var client = new WebClient())
            {                

                var fileToConvert = "c:\file-to-convert.docx";


                var data = new NameValueCollection();                

                data.Add("ApiKey", "413595149"); 

                try
                {                    
                    client.QueryString.Add(data);
                    var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);                    
                    var responseHeaders = client.ResponseHeaders;                    
                    var path = Path.Combine(@"C:\", 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);
                    }

                }


            }

使用HttpClient()的例子

    using (var client = new System.Net.Http.HttpClient())
    {
        using (var multipartFormDataContent = new MultipartFormDataContent())
        {
            var values = new[]
            {
                new KeyValuePair<string, string>("ApiKey", "YourApiKey")
            };

            foreach (var keyValuePair in values)
            {
                multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
            }

            multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(@"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');

            const string requestUri = "http://do.convertapi.com/word2pdf";

            var response = await client.PostAsync(requestUri, multipartFormDataContent);
            if (response.IsSuccessStatusCode)
            {
                var responseHeaders = response.Headers;
                var paths = responseHeaders.GetValues("OutputFileName").First();
                var path = Path.Combine(@"C:\", paths);
                File.WriteAllBytes(path, await response.Content.ReadAsByteArrayAsync());
            }
            else
            {
                Console.WriteLine("Status Code : {0}", response.StatusCode);
                Console.WriteLine("Status Description : {0}", response.ReasonPhrase);
            }

        }
    }

【讨论】:

  • 我在一个 Windows 应用商店应用程序中工作,它似乎没有 WebClient,是否有机会使用 httpclient 或其他替代方法进行 anwser?
  • 使用 HttpClient.PostAsync 示例更新的答案。
  • 哦等等,没关系,我看到了我的错误 :) 这是不完整的 "multipartFormDataContent.Add(new ByteArrayContent(fileBytes)); "
猜你喜欢
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多