2014-10-21 2 views
1

Windows 저장소 앱 프로젝트에서 Convertapi을 시도하고 있으며 .docx 파일을 보내고 답례로 PDF 파일을 가져오고 싶습니다. 완료, 이것은 내가 지금까지 가지고 있지만 작동하지 않습니다.Windows 저장소 응용 프로그램에서 convertapi 사용

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(); 

}

어떻게 보답 .pdf 파일을 .DOCX 파일을 보내고받을 내 게시물을해야합니까?

편집 :

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 메신저는 상점이 응답을 받고, 윈도우 스토어 앱에 "File.ReadAllBytes"이있을 것 같지 않기 때문에 당신의 대답은 조금 적응하기 위해 노력 : \ enter image description here

+0

를 사용하는 예. [여기] (http://stackoverflow.com/questions/16416601/c-sharp-httpclient-4-5-multipart-form-data-upload) 및 [여기] (http://stackoverflow.com/questions/)를 확인하십시오. 10339877/asp-net-webapi-how-to-perform-a-multipart-post-with-file-upload-using webapi-ht)를 참조하십시오. 해당 파일 요청에 대한 내 Fiddling을 기반으로 한 File Content의 경우 'Content-Disposition'은 'form-data'여야합니다. 이름 - "파일"; filename = ""'(대체 ). 'Content-Type은'application/msword' 일 필요가 있습니다. 확실하지 않습니다. –

답변

2

파일 스트림을 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); 
        } 

       } 


      } 

난 당신이`MultipartFormDataContent`가 아닌`FormUrlEncodedContent`를 사용 할 필요가 있다고 생각 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); 
      } 

     } 
    } 
+0

메신저가 Windows Store App에서 작동하고 있는데, WebClient가없는 것 같으며, httpclient 또는 다른 대안으로 anwser에 대한 기회가 있습니까? – Ric

+0

답변이 HttpClient.PostAsync 예제로 업데이트되었습니다. – Tomas

+0

내 게시물을 편집했지만 여전히 문제가 발생했습니다. \ – Ric

관련 문제