第28天:自订(拆成)自己的Helper辅助功能-FileHelper

我们把昨天的写入档案功能抽成一个独立静态方法,减少Action负责的逻辑,在其他地方若也用到写度档案功能,抽成独立方法,也能增加程序码重复利用性。

这边我在专案中建立一个Helpers资料夹,专门放这种重复利用的功能,并在里面新增FileHelper.cs,并建立Writer()方法,将写入档案功能移动到里面,写如完毕後回传一个资料库File类别。

public class FileHelper
{
    public static async Task<Models.File> WriterAsync(IFormFile file)
    {
        //取得使用者上传档案的原始档名
        var fileOriginName = Path.GetFileName(file.FileName);
        //取原始档名中的副档名
        var fileExt = Path.GetExtension(fileOriginName);
        //为避免使用者上传的档案名称发生重复,重新给一个乱数名称
        var fileNewName = Path.GetRandomFileName();
        //指定要写入的路径、档名和副档名
        var filePath = "/data/" + fileNewName + fileExt;

        //将使用者上传的档案写入到指定路径
        await using (var stream = System.IO.File.Create(filePath))
        {
            //执行写入
            await file.CopyToAsync(stream);
        }
        var newFile = new Models.File()
        {
            Id = Guid.NewGuid().ToString(),
            Name = fileNewName + fileExt
        };

        return newFile;
    }
}

移动完之後,我的Action会变得比较乾净如下

[HttpPost]
public async Task<IActionResult> AddProduct(AddProductViewModel productViewModel)
{
    if (ModelState.IsValid)
    {
        var file = await FileHelper.WriterAsync(productViewModel.File);
        
        var last = _context.Product.OrderByDescending(d => d.Id).FirstOrDefault();
        var product = new Product()
        {
            Id = last.Id + 1,
            Name = productViewModel.Name,
            FileId = file.Id
        };

        _context.File.Add(file);

        _context.Product.Add(product);
        _context.SaveChanges();

        return RedirectToAction("Index");
    }
    return View(productViewModel);
}

在撰写MVC的过程中,单纯只分M、V、C三个大方向责任范围其实还不够用,向档案写入、信件发送,或是显示逻辑判断等等都可以拆成可以重复使用的功能。


<<:  Day 30|Divi 功能练习 23 Video Module 影片嵌入功能

>>:  JS读书笔记30天 - Day28 MVVM概念

DAY12 - 档案类的物件关系厘清(1) - File, FileList, Blob

前端网页若要取得一个档案,大家可能第一个画面就是下面这个UI吧!是利用<input type=...

DAY1:我竟然参加铁人赛了!!!

铁人赛!!! 30天的铁人赛,先报名再说,管他有没有准备好,给自己一点磨练吧! 大家好,我简单的自我...

# Day 30 Commencement: I open at the close

哇!不知不觉就到第 30 天了,来回顾一下这 30 天的旅程吧! 简单回顾 自己订的铁人赛主题是阅读...

Day 29- 鬼斧神工 :Serverless 电商 - 实战 - 测试计画。

前言 在我们完成一项产品的时候都需要做到各种测试,并完成相关测试计画,才是一个完整的产品。 单元测试...

Day27 Gin with Colly

What is Colly? Colly是一种Golang的网路爬虫工具,而网路爬虫Web Craw...