代码之家  ›  专栏  ›  技术社区  ›  Stpete111

C#将文件上载到转换服务,然后将结果文件下载到特定文件夹

c#
  •  0
  • Stpete111  · 技术社区  · 7 年前

    我继承了一个C#脚本,它应该将pdf文件上载到 converter service 然后下载转换后的文件。但这个脚本中似乎缺少下载部分。

    代码如下:

    using System;
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using CustomScript.Api;
    
    public class Script
    {
        public static CustomScriptReturn CustomScript(CustomScriptArguments args)
        {
            using (HttpClient httpClient = new HttpClient())
                {
                  httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "token");
                  MultipartFormDataContent form = new MultipartFormDataContent();  
                  byte[] fileBytes = File.ReadAllBytes(@"C:\Users\user1\Documents\Test\Files\test1.pdf");
                  form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "test1", "test1.pdf"); 
                  HttpResponseMessage response = httpClient.PostAsync("https://pdftables.com/api?key=1234567&format=html", form).Result; 
                }
            return CustomScriptReturn.Empty();
        }
    }
    

    这个脚本在我们使用的程序中运行时没有错误,但实际上没有下载任何内容,尽管converter服务的支持人员指出这是正确的。也许问题在于 return CustomScriptReturn.Empty C# .

    要将转换后的文件下载到输入文件所在的文件路径中,需要向其中添加哪些代码?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Rob    7 年前

    当您向web服务投递邮件时,在这种情况下,将pdf转换为所选格式,转换将发生,并将转换后的数据吐回给您。这是返回数据内容的一部分。当前代码设置为始终返回

    return CustomScriptReturn.Empty();
    

    HttpResponseMessage response = httpClient.PostAsync("https://pdftables.com/api?key=1234567&format=html", form)
    

    然后,在发送回CustomScriptReturn.Empty()之前,您可以检查以确保一切正常,例如确保发送转换后的内容流的HTTP请求状态为OK,或者如果它不是send Empty

    HttpResponseMessage response = httpClient.PostAsync("https://pdftables.com/api?key=1234567&format=html", form)
    if ((int)response.StatusCode == 200)
    {
        //obviously you will need to handle converting the return data to your custom type
        return (CustomScriptReturn)response.Content.ReadAsStringAsync();
    }
    else
    {
        return CustomScriptReturn.Empty();
    }