【问题标题】:C# upload a file to conversion service then download resulting file to specific folderC# 将文件上传到转换服务,然后将生成的文件下载到特定文件夹
【发布时间】:2019-08-08 22:36:00
【问题描述】:

我继承了一个 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();
    }
}

这个脚本在我们使用的程序中运行没有错误,但实际上没有下载任何内容,尽管转换器服务的支持人员表示这是正确的。也许问题出在return CustomScriptReturn.Empty 行,但我不确定,因为我对C# 比较陌生。

需要添加什么代码才能将转换后的文件下载到与输入文件相同的文件路径?

【问题讨论】:

  • 它应该是响应变量的一部分
  • 谢谢,你能详细说明一下吗?
  • 更改 HttpResponseMessage 响应 = httpClient.PostAsync("pdftables.com/api?key=1234567&format=html", form).Result;到 HttpResponseMessage 响应 = httpClient.PostAsync("pdftables.com/api?key=1234567&format=html", form);然后在下一行做一个 var content = response.Content;并在上面设置一个断点。您可以检查 response.Content 应该包含您正在寻找的返回数据

标签: c# httpclient dotnet-httpclient


【解决方案1】:

当您对 Web 服务进行 POST 时,在这种情况下,它会将 pdf 转换为选定的格式,转换将会发生,它会将转换后的数据返回给您。这是返回数据内容的一部分。您当前的代码设置为始终返回

return CustomScriptReturn.Empty();

这也是您永远不会看到您所寻找的任何数据的部分原因。更好的方法是获得完整的响应

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

然后您可以在发回 CustomScriptReturn.Empty() 之前检查以确保一切正常,例如确保 HTTP 请求状态正常发送转换后的内容流,或者如果它不是发送 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多