Skip to content

Commit 8bc2ab4

Browse files
committed
refactor: 增加 SaveToFileAsync 扩展方法
1 parent f810deb commit 8bc2ab4

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
// Website: https://www.blazor.zone or https://argozhang.github.io/
4+
5+
namespace BootstrapBlazor.Components;
6+
7+
/// <summary>
8+
/// EditorUploadFile 扩展方法类
9+
/// </summary>
10+
public static class EditorUploadFileExtensions
11+
{
12+
/// <summary>
13+
/// 保存到文件方法
14+
/// </summary>
15+
/// <param name="upload"></param>
16+
/// <param name="fileName"></param>
17+
/// <param name="bufferSize"></param>
18+
/// <param name="token"></param>
19+
/// <returns></returns>
20+
public static async Task<bool> SaveToFileAsync(this EditorUploadFile upload, string fileName, int bufferSize = 64 * 1024, CancellationToken token = default)
21+
{
22+
var ret = false;
23+
24+
// 文件保护,如果文件存在则先删除
25+
if (File.Exists(fileName))
26+
{
27+
try
28+
{
29+
File.Delete(fileName);
30+
}
31+
catch (Exception ex)
32+
{
33+
upload.Error = ex;
34+
return ret;
35+
}
36+
}
37+
38+
var folder = Path.GetDirectoryName(fileName);
39+
if (!string.IsNullOrEmpty(folder) && !Directory.Exists(folder))
40+
{
41+
Directory.CreateDirectory(folder);
42+
}
43+
44+
using var uploadFile = File.OpenWrite(fileName);
45+
try
46+
{
47+
// 打开文件流
48+
var buffer = new byte[bufferSize];
49+
int bytesRead = 0;
50+
51+
// 开始读取文件
52+
while ((bytesRead = await upload.Stream.ReadAsync(buffer, token)) > 0)
53+
{
54+
await uploadFile.WriteAsync(buffer.AsMemory(0, bytesRead), token);
55+
}
56+
ret = true;
57+
}
58+
catch (Exception ex)
59+
{
60+
upload.Error = ex;
61+
}
62+
63+
return ret;
64+
}
65+
}

0 commit comments

Comments
 (0)