gpt4 book ai didi

c# - .NET Core 2.0 MVC 文件上传进度

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:02 27 4
gpt4 key购买 nike

所以我花了很多时间尝试为我的 .Net Core MVC 应用程序显示进度条,而官方文档并不是很有帮助。

此处的文档:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.0#uploading-large-files-with-streaming

我还想在文件到达我的 Controller 时将其上传到 Azure blob 存储。用户可以上传任意数量的文件。

这是我的上传代码:

for (int i = 0; i < videoFile.Count; i++)
{

long totalBytes = videoFile[i].Length;

byte[] buffer = new byte[16 * 1024];
using (Stream input = videoFile[i].OpenReadStream())
{
long totalReadBytes = 0;
int readBytes;

while ((readBytes = input.Read(buffer, 0, buffer.Length)) > 0)
{
totalReadBytes += readBytes;
var progress = (int)((float)totalReadBytes / (float)totalBytes * 100.0);
}
}

String videoPath = videoFile[i].FileName;

await sc.UploadBlobAsync(groupContainer, videoPath, videoFile[i]);
}

这是我的 UploadBlobAsync 方法:

public async Task<bool> UploadBlobAsync(string blobContainer, string blobName, IFormFile file) {
CloudBlobContainer container = await GetContainerAsync(blobContainer);
CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

CancellationToken cancellationToken = new CancellationToken();
IProgress<StorageProgress> progressHandler = new Progress<StorageProgress>(
progress => Console.WriteLine("Progress: {0} bytes transferred", progress.BytesTransferred)
);

using (var filestream = file.OpenReadStream()) {
await blob.UploadFromStreamAsync(filestream,
default(AccessCondition),
default(BlobRequestOptions),
default(OperationContext),
progressHandler,
cancellationToken);
}
return true;
}

我想知道的是:

  1. 据我了解,我必须执行 2 个进度条,一个用于客户端计算机到我的服务器,另一个用于从我的服务器到 Azure。这是正确的吗?

  2. 如何将每个文件的进度显示到前端?我想这将是对我在 Controller 中设置的 List[i] 的 ajax 请求?

  3. 当文件已经缓冲时,我是否在 while 循环中读取字节?如果我可以访问文件流,文件不是已经缓存在服务器上了吗?

  4. 如何利用 Azure 的 IProgress 实现在结果发生变化时将结果返回给我? Console.Writeline 似乎不起作用。

最佳答案

换个角度,你应该尝试使用blob上传的检查机制 进展,示例如下:

 var speedSummary = blobService.createBlockBlobFromStream('mycontainer', file.name, fileStream, file.size, function(error, result, response) {...}

setTimeout(function() {
if (!finishedOrError) {
var process = speedSummary.getCompletePercent();
displayProcess(process);
refreshProgress();
}
}, 200);

您可以在此处找到更多详细信息:https://github.com/Azure/azure-storage-node/issues/310

1-你只能使用一个进度条

2- 你可以使用最近在 github 上发布的基于 blob 上传的进度机制。

关于c# - .NET Core 2.0 MVC 文件上传进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50583687/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com