【发布时间】:2018-12-25 04:39:11
【问题描述】:
我有一个来自我正在尝试的插件的示例代码。
HttpResponseMessage hrm = client.PostAsync(uri, content).GetAwaiter().GetResult();
if (hrm.StatusCode == HttpStatusCode.OK)
{
MultipartMemoryStreamProvider provider = hrm.Content.ReadAsMultipartAsync().GetAwaiter().GetResult();
if (provider.Contents.Count > 0)
{
for (int i = 0; i < provider.Contents.Count; i++)
{
HttpContent rcontent = provider.Contents[i];
byte[] bytes = rcontent.ReadAsByteArrayAsync().GetAwaiter().GetResult();
File.WriteAllBytes(@"c:\temp\ConvertToPDF" + i + ".pdf", bytes);
}
}
}
此代码将 n 个文件发布到 api,并以 pdf 格式获取相同的文件作为响应。
然后将响应保存到不同的文件中。现在,MultipartMemoryStreamProvider 在Contents 集合中有 n 个文件。但是,这两个文件实际上都指向我选择的最后一个文件。
创建请求的代码
//Multipart content
MultipartContent content = new MultipartContent();
foreach (var singleFile in files)
{
//Create the StreamContent of the input file and add to the MultpartContent
StreamContent is1 = new StreamContent(singleFile.InputStream);
is1.Headers.ContentType = new MediaTypeHeaderValue(singleFile.ContentType);
is1.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
is1.Headers.ContentDisposition.Name = singleFile.FileName;
is1.Headers.ContentDisposition.FileName = singleFile.FileName;
content.Add(is1);
}
这是创建内容对象的代码。我检查了对象,它实际上包含两个不同的文件。所以,我不确定为什么下面这行会导致问题。
MultipartMemoryStreamProvider provider = hrm.Content.ReadAsMultipartAsync().GetAwaiter().GetResult();
附:插件名称是 ActivePDF DocConverter。遗憾的是它没有提供托管的演示链接,所以我不能在这里提供网址。我正在使用我的本地机器来托管该插件。
【问题讨论】:
-
所以PDF创建工作,但是你foreach返回的文件都是同一个文件?您如何检索文件?
-
其实我用的都是字节数组。它们是不同的文件。有趣的是,假设我有 abc.jpg 和 abc.png。它们都被转换并且更新的文件名都变成了它们的 abc.pdf。有趣的是,标题中更新的文件名是无用的,因为我只需要字节数组。