我有一个过程,需要从一个位置下载文件。然后,需要将该文件以10 mb的块大小发布到另一个API端点。在此过程中,无法将文件复制到服务器,必须将其流式传输到另一个端点。我有以下尝试使用的代码:
try
{
int DefaultReadValue = 10485760;
int toRead = 10485760;
int position = 0;
using (HttpClient myClient = new HttpClient())
{
//myClient.DefaultRequestHeaders.TransferEncodingChunked = true;
tranfile = await _getVaultFileData.GetVaultFileData(tranfile, token);
int fileSize = tranfile.FileSize;
using (HttpResponseMessage response = await myClient.GetAsync(tranfile.VaultFileURL, HttpCompletionOption.ResponseHeadersRead))
using (Stream readFrom = await response.Content.ReadAsStreamAsync())
{
readFrom.Position = position;
if(readFrom.Position >= fileSize)
{
fileStatus.Status = "Translation send";
fileStatus.Error = "";
return fileStatus;
}
if(fileSize - position < toRead)
{
toRead = fileSize - position;
}
int bytesRead;
byte[] buffer = new byte[toRead];
int offset = 0;
while (toRead > 0 && (bytesRead = readFrom.Read(buffer, offset, toRead)) > 0)
{
ByteArrayContent content = new ByteArrayContent(buffer);
HttpResponseMessage transcriptionPost = await myClient.PostAsync(tranfile.FileTranslationURL, content);
toRead -= bytesRead;
offset += bytesRead;
}
toRead = DefaultReadValue;
}
}
}
当我上线时 readFrom.Position =位置;
我得到了错误: 不支持指定的方法。
如果启用TransferEncodingChunked,则会出现此错误:
InnerException = {System.InvalidOperationException:“传输编码:分块”标头在未指定内容对象时无法使用。}
我需要做什么才能分块读取流以发布到另一个端点?