Blazor 附件上传和下载功能

效果图

Blazor 附件上传和下载功能_第1张图片

@page "/uploadFile"
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment WebHostEnvironment
@inject ToastService ToastService
@inject DownloadService DownloadService

UploadFile

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
using System.Net.Http;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Virtualization;
using Microsoft.JSInterop;
using BlazorApp;
using BlazorApp.Shared;
using BootstrapBlazor.Components;
using System.Diagnostics.CodeAnalysis;

namespace BlazorApp.Pages
{
    public partial class UploadFile
    {
        [NotNull]
        private Modal? Modal { get; set; }

        private CancellationTokenSource? ReadToken { get; set; }

        //文件大小200MB
        private static long MaxFileLength => 200 * 1024 * 1024;

        private void ButtonClick(MouseEventArgs e)
        {
            this.Modal.Toggle();
        }
        //下载
        private async Task OnDownload(BootstrapBlazor.Components.UploadFile item)
        {
            try
            {
                //文件上传路径,在wwwroot路径下
                //item.PrevUrl这个是上传的时候复制的,只能用作临时使用,从数据库读取的是另一种实现方式
                String filePath = WebHostEnvironment.WebRootPath + item.PrevUrl.Replace("/", "\\");

                await using var stream = File.OpenRead(filePath);
                await DownloadService.DownloadFromStreamAsync(item.File.Name, stream);
                await ToastService.Success("下载成功");
            }
            catch (FileNotFoundException msg)
            {
                await ToastService.Error("下载", msg.Message);
            }
        }


        //点击上传
        private async Task OnClickToUpload(BootstrapBlazor.Components.UploadFile file)
        {
            await SaveToFile(file);
        }
        //上传
        private async Task SaveToFile(BootstrapBlazor.Components.UploadFile file)
        {
            // Server Side 使用
            // Web Assembly 模式下必须使用 webapi 方式去保存文件到服务器或者数据库中
            // 生成写入文件名称
            var ret = false;
            //文件上传路径,在wwwroot路径下
            String filePath = WebHostEnvironment.WebRootPath + "\\uploadFiles";
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            //保存到服务器的名字
            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.File.Name);
            var saveFilePath = Path.Combine(filePath, fileName);
            ReadToken ??= new CancellationTokenSource();
            //保存成功
            ret = await file.SaveToFileAsync(saveFilePath, MaxFileLength, ReadToken.Token);

            //把fileName到存数据库中,或者读取数据


            if (ret)
            {
                //下载地址
                file.PrevUrl = "/uploadFiles/" + fileName;
                await ToastService.Success("上传文件成功");
            }
            else
            {
                var errorMessage = $"{"保存文件失败"} {file.OriginFileName}";
                file.Code = 1;
                file.Error = errorMessage;
                await ToastService.Error("上传文件", errorMessage);
            }
            return ret;
        }
    }
}

你可能感兴趣的:(Blazor,C#,ui,xhtml,前端)