33// See the LICENSE file in the project root for more information.
44// Maintainer: Argo Zhang([email protected] ) Website: https://www.blazor.zone 55
6+ using Newtonsoft . Json . Linq ;
7+
68namespace BootstrapBlazor . Server . Components . Samples ;
79
810/// <summary>
911/// CardUpload sample code
1012/// </summary>
11- public partial class UploadCards
13+ public partial class UploadCards : IDisposable
1214{
1315 private List < UploadFile > DefaultFormatFileList { get ; } =
1416 [
@@ -30,6 +32,7 @@ public partial class UploadCards
3032 ] ;
3133
3234 private static long MaxFileLength => 5 * 1024 * 1024 ;
35+ private CancellationTokenSource ? _token ;
3336
3437 private async Task OnCardUpload ( UploadFile file )
3538 {
@@ -46,12 +49,65 @@ private async Task OnCardUpload(UploadFile file)
4649 {
4750 // 模拟保存成功
4851 await Task . Delay ( 100 ) ;
49- // await SaveToFile(file);
52+ await SaveToFile ( file ) ;
5053 await ToastService . Success ( Localizer [ "UploadsFileMsg" ] , $ "{ file . File ! . Name } { Localizer [ "UploadsSuccess" ] } ") ;
5154 }
5255 }
5356 }
5457
58+ private async Task SaveToFile ( UploadFile file )
59+ {
60+ // Server Side 使用
61+ // Web Assembly 模式下必须使用 WebApi 方式去保存文件到服务器或者数据库中
62+ // 生成写入文件名称
63+ if ( ! string . IsNullOrEmpty ( WebsiteOption . CurrentValue . WebRootPath ) )
64+ {
65+ var uploaderFolder = Path . Combine ( WebsiteOption . CurrentValue . WebRootPath , "images" , "uploader" ) ;
66+ file . FileName = $ "{ Path . GetFileNameWithoutExtension ( file . OriginFileName ) } -{ DateTimeOffset . Now : yyyyMMddHHmmss} { Path . GetExtension ( file . OriginFileName ) } ";
67+ var fileName = Path . Combine ( uploaderFolder , file . FileName ) ;
68+
69+ _token ??= new CancellationTokenSource ( ) ;
70+ try
71+ {
72+ var ret = await file . SaveToFileAsync ( fileName , MaxFileLength , _token . Token ) ;
73+
74+ if ( ret )
75+ {
76+ // 保存成功
77+ file . PrevUrl = $ "{ WebsiteOption . CurrentValue . AssetRootPath } images/uploader/{ file . FileName } ";
78+ }
79+ else
80+ {
81+ var errorMessage = $ "{ Localizer [ "UploadsSaveFileError" ] } { file . OriginFileName } ";
82+ file . Code = 1 ;
83+ file . Error = errorMessage ;
84+ await ToastService . Error ( Localizer [ "UploadFile" ] , errorMessage ) ;
85+ }
86+ }
87+ catch ( OperationCanceledException )
88+ {
89+
90+ }
91+ }
92+ else
93+ {
94+ file . Code = 1 ;
95+ file . Error = Localizer [ "UploadsWasmError" ] ;
96+ await ToastService . Information ( Localizer [ "UploadsSaveFile" ] , Localizer [ "UploadsSaveFileMsg" ] ) ;
97+ }
98+ }
99+
100+ /// <summary>
101+ /// <inheritdoc/>
102+ /// </summary>
103+ public void Dispose ( )
104+ {
105+ _token ? . Cancel ( ) ;
106+ _token ? . Dispose ( ) ;
107+ _token = null ;
108+ GC . SuppressFinalize ( this ) ;
109+ }
110+
55111 private List < AttributeItem > GetAttributes ( ) =>
56112 [
57113 new ( )
0 commit comments