我想从客户机上传大量数据到web服务器。我直接跳到pushstreamcontent,这样就可以直接写入流,因为结果大小不一,而且可能很大。
流程如下:
User runs query > Reader Ready Event Fires > Begin Upload
一旦启动ready事件,监听器将接收它并在结果集上迭代,以多部分形式上载数据:
Console.WriteLine("Query ready, uploading");
byte[] buffer = new byte[1024], form = new byte[200];
int offset = 0, byteCount = 0;
StringBuilder rowBuilder = new StringBuilder();
string builderS;
var content = new PushStreamContent(async (stream, httpContent, transportContext) =>
//using (System.IO.Stream stream = new System.IO.FileStream("test.txt", System.IO.FileMode.OpenOrCreate))
{
int bytes = 0;
string boundary = createFormBoundary();
httpContent.Headers.Remove("Content-Type");
httpContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
await stream.WriteAsync(form, 0, form.Length);
form = System.Text.Encoding.UTF8.GetBytes(createFormElement(boundary, "file"));
await stream.WriteAsync(form, 0, form.Length);
await Task.Run(async () =>
{
foreach (var row in rows)
{
for (int i = 0; i < row.Length; i++)
{
rowBuilder.Append(row[i].Value);
if (i + 1 < row.Length)
rowBuilder.Append(',');
else
{
rowBuilder.Append("\r\n");
}
}
builderS = rowBuilder.ToString();
rowBuilder.Clear();
byteCount = System.Text.Encoding.UTF8.GetByteCount(builderS);
bytes += byteCount;
if (offset + byteCount > buffer.Length)
{
await stream.WriteAsync(buffer, 0, offset);
offset = 0;
if (byteCount > buffer.Length)
{
System.Diagnostics.Debug.WriteLine("Expanding buffer to {0} bytes", byteCount);
buffer = new byte[byteCount];
}
}
offset += System.Text.Encoding.UTF8.GetBytes(builderS, 0, builderS.Length, buffer, offset);
}
});
await stream.WriteAsync(buffer, 0, offset);
form = System.Text.Encoding.UTF8.GetBytes(boundary);
await stream.WriteAsync(form, 0, form.Length);
await stream.FlushAsync(); //pretty sure this does nothing
System.Diagnostics.Debug.WriteLine("Wrote {0}.{1} megabytes of data", bytes / 1000000, bytes % 1000000);
我认为如果我是服务器,上面的代码会很好,只需添加
stream.Close();
就可以完成它,但是由于我是这里的客户端,关闭它会导致错误(TaskCancelled
)。等待读取也没有任何作用,我推测是因为pushstreamcontent不会结束请求,除非我显式地关闭流。也就是说,写一个文件会产生我希望上传的内容,所以一切都写得很好。有什么我能做的吗?我可能完全误用了
PushStreamContent
,但看起来这应该是一个合适的用例。 最佳答案
因此,这个解决方案一开始有点混乱,但似乎有道理,也许更重要的是,它起作用:
using(var content = new MultipartFormDataContent())
{
var pushContent = new PushStreamContent(async (stream, httpContent, transportContext) =>
{
//do the stream writing stuff
stream.Close();
});
content.add(pushContent);
//post, put, etc. content here
}
这是因为传递给
PushStreamContent
方法的流不是实际的请求流,而是由HttpClient
处理的流,就像向请求流添加文件一样。因此,关闭它表示HttpContent
这一部分的输入结束,并允许完成请求。关于c# - 使用PushStreamContent从HTTPClient上传,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35283334/