myesn

myEsn2E9

hi
github

ABP: 使用 BLOB Storing (File System Provider)完成文件上传和下载

安装依赖#

?.Domain 项目中执行:

abp add-package Volo.Abp.BlobStoring.FileSystem

命令执行后,会自动:

  1. 在项目中安装 NuGet 包 Volo.Abp.BlobStoring.FileSystem
  2. ?DomainModule.cs 中添加以下代码:
using Volo.Abp.BlobStoring.FileSystem;

[DependsOn(typeof(AbpBlobStoringFileSystemModule))]
public class ?DomainModule : AbpModule { }

Setting up Blob Storaging#

在使用 Blob 存储之前,我们需要创建 Blob Container。

?.Domain\BlobStoring 目录下创建一个 FileContainer 的类,内容如下:

using Volo.Abp.BlobStoring;

namespace ?.BlobStoring
{
    [BlobContainerName("file-container")]
    public class FileContainer
    {

    }
}

在此之后,我们可以在 ?.Web 项目的 ?WebModule.cs 文件中的方法 ConfigureServices 下配置 AbpBlobStoringOptions

public override void ConfigureServices(ServiceConfigurationContext context)
{
    ...
    ConfigureBlobStoring();
}

private void ConfigureBlobStoring()
{
    Configure<AbpBlobStoringOptions>(options =>
    {
        options.Containers.Configure<MiaoXinFileContainer>(container =>
        {
            container.UseFileSystem(fileSystem =>
            {
                fileSystem.BasePath = AppDomain.CurrentDomain.BaseDirectory;
            });
        });
    });
}    

如果在 Debug 模式下运行上传文件,那么文件将会被保存到 ?.Web\bin\Debug\net8.0\host\file-container 目录中
文件路径计算:https://docs.abp.io/en/abp/latest/Blob-Storing-File-System#file-path-calculation

Creating Application Layer#

在创建 Application Service 之前,我们需要创建一些 Application Service 使用的 DTO。

在项目 ?.Application.Contracts 中创建以下 DTO:

// BlobDto.cs
using System.ComponentModel.DataAnnotations;

namespace ?.Dtos
{
    public class BlobDto
    {
        public byte[] Content { get; set; }

        public string Name { get; set; }
    }

    public class GetBlobRequestDto
    {
        [Required]
        public string Name { get; set; }
    }

    public class SaveBlobInputDto
    {
        public byte[] Content { get; set; }

        [Required]
        public string Name { get; set; }
    }
}

继续在创建 DTO 的项目中创建一个 IFileService.cs 接口:

using ?.Dtos;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;

namespace ?
{
    public interface IFileService: IApplicationService
    {
        Task SaveBlobAsync(SaveBlobInputDto input);

        Task<BlobDto> GetBlobAsync(GetBlobRequestDto input);
    }
}

然后,我们可以创建的 Application Service。

在项目 ?.Application 中创中建 FileAppService.cs

using ?.BlobStoring;
using ?.Dtos;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.BlobStoring;

namespace ?
{
    public class FileService : ApplicationService, IFileService
    {
        private readonly IBlobContainer<FileContainer> _fileContainer;

        public FileService(IBlobContainer<FileContainer> fileContainer)
        {
            _fileContainer = fileContainer;
        }

        public async Task<BlobDto> GetBlobAsync(GetBlobRequestDto input)
        {
            var blob = await _fileContainer.GetAllBytesAsync(input.Name);

            return new BlobDto
            {
                Name = input.Name,
                Content = blob
            };
        }

        public async Task SaveBlobAsync(SaveBlobInputDto input)
        {
            await _fileContainer.SaveAsync(input.Name, input.Content, true);
        }
    }
}

我们完成了这个项目的应用层。之后,我们将为 API 创建一个 Controller,并用 Razor Page 来实现 UI。

Creating Controller#

在项目 ?.HttpApi 中创建 FileController.cs

using ?.Dtos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Threading.Tasks;
using Volo.Abp.Guids;

namespace ?.Controllers
{
    [Route("api/[controller]")]
    public class FileController : MiaoXinController
    {
        private readonly IFileService _fileService;
        private readonly IGuidGenerator _guidGenerator;

        public FileController(IFileService fileService, IGuidGenerator guidGenerator)
        {
            _fileService = fileService;
            _guidGenerator = guidGenerator;
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="folder">目录名称(可为空)</param>
        /// <param name="file">单个文件</param>
        /// <returns></returns>
        [HttpPost("upload")]
        public async Task<IActionResult> UploadAsync(string? folder, IFormFile file)
        {
            var saveFileName = $"{_guidGenerator.Create()}{Path.GetExtension(file.FileName)}";
            var fileBytes = await file.GetAllBytesAsync();

            await _fileService.SaveBlobAsync(new SaveBlobInputDto
            {
                Name = Path.Combine(folder ?? string.Empty, saveFileName),
                Content = fileBytes,
            });

            return Ok(new
            {
                Name = saveFileName
            });
        }

        /// <summary>
        /// 下载单个文件
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns></returns>
        [HttpGet("download/{fileName}")]
        public async Task<IActionResult> DownloadAsync([FromRoute] string fileName)
        {
            var fileDto = await _fileService.GetBlobAsync(new Dtos.GetBlobRequestDto { Name = fileName });

            return File(fileDto.Content, "application/octet-stream", fileDto.Name);
        }
    }
}

DownloadAsync 用于将文件从服务器发送到客户端。
此接口只需要一个 string 参数,然后我们使用该参数来获取存储的 Blob。如果 blob 存在,则返回结果 File ,以便可以开始下载过程。

Creating User Interface#

我们将只创建一个页面来证明下载和上传操作正常。

?.Web 项目的 Dtos 目录中创建 UploadFileDto

// UploadFileDto.cs
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace ?.Web.Dtos
{
    public class UploadFileDto
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        [Required]
        [DisplayName("文件名称")]
        public string Name { get; set; }

        /// <summary>
        /// 单个文件
        /// </summary>
        [Required]
        [DisplayName("文件")]
        public IFormFile File { get; set; }
    }
}

然后在 Pages 目录中创建名称为 Files 的目录。再创建一个 Razor page,该页面命名 Index 。

using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc.UI.RazorPages;

namespace ?.Web.Pages.Files
{
    public class Index : ?PageModel
    {
        [BindProperty]
        public UploadFileDto UploadFileDto { get; set; }

        private readonly IFileService _fileService;

        public bool Uploaded { get; set; } = false;

        public Index(IFileService fileService)
        {
            _fileService = fileService;
        }

        public void OnGet()
        {

        }

        public async Task<IActionResult> OnPostAsync()
        {
            using (var memoryStream = new MemoryStream())
            {
                await UploadFileDto.File.CopyToAsync(memoryStream);

                await _fileService.SaveBlobAsync(
                    new SaveBlobInputDto
                    {
                        Name = UploadFileDto.Name,
                        Content = memoryStream.ToArray()
                    }
                );
            }

            return Page();
        }
    }
}

Index.cshtml:

@page
@model ?.Web.Pages.Files.Index

@section scripts{
    <abp-script src="/Pages/Files/Index.js" />
}

<abp-card>
    <abp-card-header>
        <h3>File Upload and Download</h3>
    </abp-card-header>
    <abp-card-body>
        <abp-row>
            <abp-column>
                <h3>Upload File</h3>
                <hr />
                <form method="post" enctype="multipart/form-data">
                    <abp-input asp-for="UploadFileDto.Name"></abp-input>

                    <abp-input asp-for="UploadFileDto.File"></abp-input>

                    <input type="submit" class="btn btn-info" />
                </form>
            </abp-column>

            <abp-column style="border-left: 1px dotted gray">
                <h3>Download File</h3>
                <hr />
                <form id="DownloadFile">
                    <div class="form-group">
                        <label for="fileName">Filename</label><span> * </span>
                        <input type="text" id="fileName" name="fileName" class="form-control ">
                    </div>

                    <input type="submit" class="btn btn-info"/>
                </form>
            </abp-column>
        </abp-row>
    </abp-card-body>
</abp-card>

我们将页面垂直划分,左侧用于上传,右侧用于下载。我们使用 ABP Tag Helpers 来创建页面。

在与 Index.cshtml 文件相同的目录下创建 Index.js 文件。

$(function () {
  var DOWNLOAD_ENDPOINT = "/api/download";

  var downloadForm = $("form#DownloadFile");

  downloadForm.submit(function (event) {
    event.preventDefault();

    var fileName = $("#fileName").val().trim();

    var downloadWindow = window.open(
      DOWNLOAD_ENDPOINT + "/" + fileName,
      "_blank"
    );
    downloadWindow.focus();
  });

  $("#UploadFileDto_File").change(function () {
    var fileName = $(this)[0].files[0].name;

    $("#UploadFileDto_Name").val(fileName);
  });
});

此 jQuery 代码用于下载。此外,我们还编写了一个简单的代码,以便在用户选择文件时自动填充 Filename 输入。

使用 Ajax 上传和预览图片#

如果表单中某个属性的值需要上传文件后才能得到,那么这个表单就不能用 abp 提供的 <abp-dynamic-form> tag helper,需要自己手动编写表单,可以参考 Pages/Customers 目录中的 CreateModalEditModal(这个是我自己的页面,时间关系,暂时不整理出来了)。

添加通用文件上传代码:

/**
 * 初始化所有上传文件输入框的交互,注意: html 一定要按照上面的规则顺序编写
 */
function initialAllUploadFileInputs() {
    // 注意这里回调函数最好是 function,而不是箭头函数,否则 this 指向会出错
    $('form input[type="file"]').on('change', async function (e) {
        var file = e.target.files[0];
        if (!file) {
            // 取消文件选择后,也要清空隐藏的 input 控件值、图片预览
            $(this).next().val('');
            $(this).nextAll('img').removeAttr('src');
            return;
        }

        // 上传文件
        const result = await uploadFile(null, e.target.files[0]);

        // 注意 input=hidden 控件必须放在当前 input=file 控件之后,否则无法设置表单控件值
        $(this).nextAll('input[type=hidden]').val(result.name);
        // 图片预览
        $(this).nextAll('img').attr('src', abp.appPath + 'api/File/download/' + result.name);
    });
}

/**
 * 调用 HTTP Api 上传文件
 * @param {any} folder  目录,可为空
 * @param {any} file e.target.files[0]
 * @returns
 */
async function uploadFile(folder, file) {
    const formData = new FormData();
    if (folder) {
        formData.append('folder', folder);
    }

    formData.append('file', file);

    return await miaoXin.controllers.file.upload({}, {
        data: formData,
        // 必须false才会自动加上正确的Content-Type
        contentType: false,
        // 必须false才会避开jQuery对 FormData 的默认处理
        // XMLHttpRequest 会对 FormData 进行正确的处理
        processData: false,
    });
}

然后在页面执行:

$(() => {
    initialAllUploadFileInputs();
});

调用 initialAllUploadFileInputs 后会为所有的 input=file 控件绑定 change 事件,当 change 后会自动上传,并设置预览图片,但是要求 html 格式必须符合下面的顺序规范:

如果是创建表单:

@* 注意,label、input=file、input=hidden、img 标签必须按照顺序出现,因为背后的 JavaScript 代码依赖于它们的顺序 *@
<div class="mb-3">
    <label class="form-label" for="CreateCustomerDto_IdImageFrontId_FileInput">个人证件照片正面</label>
    <input type="file" class="form-control" id="CreateCustomerDto_IdImageFrontId_FileInput" />

    <input type="hidden" name="CreateCustomerDto.IdImageFrontId" />
    <img style="width: 100%; max-height: 200px; margin-top: 2px;" />
</div>

如果是更新表单:

@* 注意,label、input=file、input=hidden、img 标签必须按照顺序出现,因为背后的 JavaScript 代码依赖于它们的顺序 *@
<div class="mb-3">
    <label class="form-label" for="UpdateCustomerDto_IdImageFrontId_FileInput">个人证件照片正面</label>
    <input type="file" class="form-control" id="UpdateCustomerDto_IdImageFrontId_FileInput" disabled="@Model.ReadOnly" />

    <input type="hidden" name="UpdateCustomerDto.IdImageFrontId" value="@Model.UpdateCustomerDto.IdImageFrontId" />

    <img src="@($"api/File/download/{Model.UpdateCustomerDto.IdImageFrontId}")" style="width: 100%; max-height: 200px; margin-top: 2px;" />
</div>

Result#

完成代码教程后,运行 ?.Web 项目,并在浏览器中打开 /Files 页面 。可以上传任何名称的任何文件,也可以下载这些上传的文件。

image

参考#

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.