c# - 自定义 ProgressableStreamContent 不起作用
问题描述
你好根据:https ://gist.github.com/HirbodBehnam/272aa5e4b82c2fb05583d095f2224861
我实现了这个:
我的电话:
public async Task<string> UploadFiles(FileInfo fileInfo)
{
string res = null;
using (var client = new HttpClient())
using (var multiForm = new MultipartFormDataContent())
{
client.Timeout = TimeSpan.FromMinutes(5); // You may need this if you are uploading a big file
var file = new ProgressableStreamContent(new StreamContent(File.OpenRead(fileInfo.FullName))
, (sent, total) => {
//Console.SetCursorPosition(1, 0); // Remove last line
Console.WriteLine("\bUploading " + ((float)sent / total) * 100f);
});
multiForm.Add(file, fileInfo.Name, fileInfo.Name); // Add the file
var uploadServiceBaseAdress = "http://10.0.2.2:44560/PostFiles/";
var response = await client.PostAsync(uploadServiceBaseAdress, multiForm);
Console.WriteLine(response.StatusCode);
if (response.StatusCode == HttpStatusCode.OK)
{
res = await response.Content.ReadAsStringAsync();
Console.WriteLine(res);
}
return res;
}
我的课:可进步的流内容
internal class ProgressableStreamContent:HttpContent
{
/// <summary>
/// Lets keep buffer of 20kb
/// </summary>
private const int defaultBufferSize = 5 * 4096;
private HttpContent content;
private int bufferSize;
//private bool contentConsumed;
private Action<long, long> progress;
public ProgressableStreamContent(HttpContent content, Action<long, long> progress) : this(content, defaultBufferSize, progress) { }
public ProgressableStreamContent(HttpContent content, int bufferSize, Action<long, long> progress)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
this.content = content;
this.bufferSize = bufferSize;
this.progress = progress;
foreach (var h in content.Headers)
{
this.Headers.Add(h.Key, h.Value);
}
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return Task.Run(async () =>
{
var buffer = new Byte[this.bufferSize];
long size;
TryComputeLength(out size);
var uploaded = 0;
using (var sinput = await content.ReadAsStreamAsync())
{
while (true)
{
var length = sinput.Read(buffer, 0, buffer.Length);
if (length <= 0) break;
//downloader.Uploaded = uploaded += length;
uploaded += length;
progress?.Invoke(uploaded, size);
//System.Diagnostics.Debug.WriteLine($"Bytes sent {uploaded} of {size}");
stream.Write(buffer, 0, length);
stream.Flush();
}
}
stream.Flush();
});
}
protected override bool TryComputeLength(out long length)
{
length = content.Headers.ContentLength.GetValueOrDefault();
return true;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
content.Dispose();
}
base.Dispose(disposing);
}
}
它绑定在 ProgressableStreamContent 的构造函数中。然后回到我的上传文件方法,但是当它返回时它崩溃了:Operation not supported on this platform
。
我认为有些东西我不明白,我没有找到任何与此相关的文档。那么你能解释一下怎么了吗?
解决方案
您可以尝试这样的事情:
using (var multiForm = new MultipartFormDataContent())
{
byte[] fileBytes = null;// your file
var file = new ByteArrayContent(fileBytes);
...
multiForm.Add(file, fileInfo.Name, fileInfo.Name); // Add the file
var progressContent = new ProgressableStreamContent(multiForm,4096, (sent, total) => {
//Console.SetCursorPosition(1, 0); // Remove last line
Console.WriteLine("\bUploading " + ((float)sent / total) * 100f);
});
...
var response = await client.PostAsync(uploadServiceBaseAdress, progressContent );
...
}
推荐阅读
- ios - N 个集合视图单元格 - 自动调整大小以显示屏幕中的所有单元格
- wordpress - 抛出新的错误。TypeError('ERR_INVALID_ARG_TYPE', 'original', 'function'); 当我尝试在本地 xubuntu 上运行 wp-env 时出错
- android - Firebase 中数据库的警告消息
- rotation - 沿给定轴旋转网格,然后再次沿不同轴正确旋转
- java - 在项目或库中找不到清单中引用的类 com.example.bottomnav.ClientBottomNav
- mysql - nodejs mysql验证值是否存在
- excel - 如何在for循环中解析具有多张工作表的Excel文件
- python-3.x - Python3 无法使用 lxml.etree.find 获取 XML 元素值
- javascript - 我将如何为我的 Electron 应用程序创建后端
- c - 在父目录中为源文件创建 Makefile