当前位置: 首页 > news >正文

使用 ASP.NET Core wwwroot 上传和存储文件

在 ASP.NET Core 应用程序中上传和存储文件是用户个人资料、产品目录等功能的常见要求。本指南将解释使用wwwroot存储图像(可用于文件)的过程以及如何在应用程序中处理图像上传。

步骤 1:设置项目环境

确保您的 ASP.NET 项目中具有必要的依赖项和环境设置。这包括配置服务和wwwroot在项目中创建用于静态文件服务的文件夹。 

静态文件服务是将未编译的内容(如图像、CSS 和 JavaScript 文件)直接从服务器传送到客户端浏览器的过程。

第 2 步:定义模型和 DTO

创建模型和数据传输对象 (DTO) 来处理图像元数据和其他相关数据。 

public class Branch
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string? ImagePath { get; set; } // Path to the stored image

步骤 3:配置图像上传的控制器操作 

实现控制器操作来处理上传图像的 HTTP 请求。 

上传并存储图像

1、为图像生成一个唯一的文件名。

2、将图像存储在wwwroot/images目录中(或任何其他目录中)。

3、在数据库中保存图像路径。

[HttpPost]
public async Task<IActionResult> AddBranch([FromForm] AddBranchDto addBranchDto, IFormFile image)
{
    string? imagePath = null;
    if (image != null)
    {
        var fileName = $"{Guid.NewGuid()}-{Path.GetFileName(image.FileName)}";
        var filePath = Path.Combine(_webHostEnvironment.WebRootPath, "images", fileName);

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await image.CopyToAsync(stream);
        }

        imagePath = Path.Combine("images", fileName);
    }

    var branchEntity = new Branch
    {
        Name = addBranchDto.Name,
        Location = addBranchDto.Location,
        Email = addBranchDto.Email,
        Phone = addBranchDto.Phone,
        ImagePath = imagePath
    };

    _dbContext.Branches.Add(branchEntity);
    await _dbContext.SaveChangesAsync();

    return Ok(branchEntity);
}

更新图像

处理图像的更新,包括在上传新图像时删除旧图像。

[HttpPut("{id:guid}")]
public async Task<IActionResult> UpdateBranch(Guid id, [FromForm] UpdateBranchDto updateBranchDto, IFormFile image)
{
    var branch = _dbContext.Branches.Find(id);
    if (branch == null)
        return NotFound();

    if (image != null)
    {
        var fileName = $"{Guid.NewGuid()}-{Path.GetFileName(image.FileName)}";
        var filePath = Path.Combine(_webHostEnvironment.WebRootPath, "images", fileName);

        if (!string.IsNullOrEmpty(branch.ImagePath))
        {
            var oldFilePath = Path.Combine(_webHostEnvironment.WebRootPath, branch.ImagePath.Replace('/', '\\'));
            if (System.IO.File.Exists(oldFilePath))
            {
                System.IO.File.Delete(oldFilePath);
            }
        }

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            await image.CopyToAsync(stream);
        }

        branch.ImagePath = Path.Combine("images", fileName);
    }

    branch.Name = updateBranchDto.Name;
    branch.Location = updateBranchDto.Location;
    branch.Email = updateBranchDto.Email;
    branch.Phone = updateBranchDto.Phone;

    await _dbContext.SaveChangesAsync();

    return Ok(branch);
}

步骤 4:提供静态文件 

配置应用程序以从wwwroot目录提供静态文件。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles(); // Enable static file serving

    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

步骤 5:前端集成

在您的前端(例如,Angular)中,实现表单来处理图像上传。

<form [formGroup]="branchForm" (ngSubmit)="onSubmit()">
  <!-- Other form fields -->
  <mat-label>Image</mat-label>
  <input type="file" formControlName="image" (change)="onFileChange($event)" />
  <button type="submit">Save</button>
</form>

处理文件变更及提交

onFileChange(event: any): void {
    const file = event.target.files[0];
    if (file) {
        this.selectedFile = file;
    }
}

onSubmit(): void {
    if (this.branchForm.valid) {
        const formData = new FormData();
        Object.keys(this.branchForm.value).forEach(key => {
            formData.append(key, this.branchForm.value[key]);
        });

        if (this.selectedFile) {
            formData.append('image', this.selectedFile);
        }

        if (this.isEditMode) {
            this.branchService.updateBranch(this.branchId, formData).subscribe();
        } else {
            this.branchService.addBranch(formData).subscribe();
        }
    }
}

结论

        通过遵循这些步骤,您可以成功地将具有唯一名称的图像上传并存储在wwwrootASP.NET 应用程序的目录中,从而确保有效地管理和检索图像。

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。   

http://www.lryc.cn/news/513744.html

相关文章:

  • 【每日学点鸿蒙知识】人脸活体检测、NodeController刷新、自动关闭输入框、Row设置中间最大宽、WebView单例
  • Android TV端弹出的PopupWindow没有获取焦点
  • 从0开始的docker镜像制作-ubuntu22.04
  • 1Panel自建RustDesk服务器方案实现Windows远程macOS
  • STM32完全学习——使用定时器1精确延时
  • 深度学习——损失函数汇总
  • 1、单片机寄存器-io输入实验笔记
  • 记忆旅游系统|Java|SSM|VUE| 前后端分离
  • CentOS7下的 OpenSSH 服务器和客户端
  • RabbitMQ基础篇之Java客户端 Topic交换机
  • 微服务-Sentinel新手入门指南
  • 传统听写与大模型听写比对
  • http性能测试命令ab
  • 前端:轮播图常见的几种实现方式
  • Pytest基础01: 入门demo脚本
  • ruoyi 多租户 开启后针对某一条sql不适用多租户; 若依多租户sql规则修改
  • driftingblues6靶机
  • Neo4j GDS 2.0 安装与配置
  • A*算法与人工势场法结合的路径规划(附MATLAB源码)
  • BootstrapTable处理表格
  • UniApp 打开文件工具,获取文件类型,判断文件类型
  • docker-开源nocodb,使用已有数据库
  • Mysql COUNT() 函数详解
  • 单周期CPU电路设计
  • 从零开始采用命令行创建uniapp vue3 ts springboot项目
  • 跟着逻辑先生学习FPGA-实战篇第一课 6-1 LED灯闪烁实验
  • springboot 跨域配置
  • C语言宏和结构体的使用代码
  • 微信小程序 覆盖组件cover-view
  • 【Redis知识】Redis进阶-redis还有哪些高级特性?