You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用.NET Core WebAPI上传文件/图片并保存至MySQL数据库?

Got it, let's tackle these two .NET Core WebAPI tasks step by step — saving images to a database and uploading files to MySQL. I'll break down each part with concrete, copy-pasteable code you can adapt to your project.

1. Save Images to Database via .NET Core WebAPI

This approach works for any relational database (SQL Server, MySQL, etc.) since we're storing the image as a byte array.

Step 1: Define the Image Entity

First, create an entity class to represent the image in your database:

using System.ComponentModel.DataAnnotations;

public class ImageEntity
{
    [Key]
    public int Id { get; set; }
    
    [Required]
    public string FileName { get; set; }
    
    [Required]
    public string ContentType { get; set; } // e.g., image/jpeg, image/png
    
    [Required]
    public byte[] Data { get; set; } // The actual image bytes
}

Step 2: Configure Your DbContext

Add the DbSet for your image entity and set up your database connection (we'll cover MySQL-specific config in the next section):

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
    
    public DbSet<ImageEntity> Images { get; set; }
}

Step 3: Build the Image Upload Controller

Create a WebAPI controller with a POST endpoint to handle image uploads:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[Route("api/[controller]")]
[ApiController]
public class ImagesController : ControllerBase
{
    private readonly AppDbContext _context;

    public ImagesController(AppDbContext context)
    {
        _context = context;
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No image file provided.");

        // Validate file type (optional but recommended)
        var allowedContentTypes = new[] { "image/jpeg", "image/png", "image/gif" };
        if (!allowedContentTypes.Contains(file.ContentType))
            return BadRequest("Only JPG, PNG, and GIF files are allowed.");

        // Convert file to byte array
        using var memoryStream = new MemoryStream();
        await file.CopyToAsync(memoryStream);
        var imageBytes = memoryStream.ToArray();

        // Create and save the image entity
        var image = new ImageEntity
        {
            FileName = file.FileName,
            ContentType = file.ContentType,
            Data = imageBytes
        };

        _context.Images.Add(image);
        await _context.SaveChangesAsync();

        return Ok(new { ImageId = image.Id, Message = "Image uploaded successfully." });
    }
}

2. Upload Files to MySQL Database via .NET Core WebAPI

This is similar to the image upload, but we'll focus on MySQL-specific setup and a generic file entity (works for any file type: PDFs, docs, etc.).

Step 1: Install Required NuGet Packages

First, add these packages to your project (via NuGet Package Manager or CLI):

dotnet add package Pomelo.EntityFrameworkCore.MySql
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson

Step 2: Define the File Entity

Create a generic file entity for MySQL:

using System.ComponentModel.DataAnnotations;

public class UploadedFile
{
    [Key]
    public int Id { get; set; }
    
    [Required]
    public string FileName { get; set; }
    
    [Required]
    public string ContentType { get; set; } // e.g., application/pdf, text/plain
    
    public long FileSize { get; set; } // Size in bytes
    
    [Required]
    public byte[] FileData { get; set; } // The file content as bytes
}

Step 3: Configure DbContext for MySQL

Update your AppDbContext and configure the MySQL connection in your Program.cs (for .NET 6+):

// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add DbContext with MySQL
builder.Services.AddDbContext<AppDbContext>(options =>
{
    var connectionString = builder.Configuration.GetConnectionString("MySQLConnection");
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});

// ... rest of your Program.cs setup

Don't forget to add the MySQL connection string to appsettings.json:

{
  "ConnectionStrings": {
    "MySQLConnection": "server=localhost;database=YourDbName;user=root;password=YourPassword;"
  }
}

Step 4: Build the File Upload Controller

Create a controller for generic file uploads:

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

[Route("api/[controller]")]
[ApiController]
public class FilesController : ControllerBase
{
    private readonly AppDbContext _context;

    public FilesController(AppDbContext context)
    {
        _context = context;
    }

    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile(IFormFile file)
    {
        if (file == null || file.Length == 0)
            return BadRequest("No file provided.");

        // Optional: Set a maximum file size (e.g., 10MB)
        var maxFileSize = 10 * 1024 * 1024; // 10MB
        if (file.Length > maxFileSize)
            return BadRequest($"File size exceeds {maxFileSize / (1024*1024)}MB limit.");

        // Read file into byte array
        using var memoryStream = new MemoryStream();
        await file.CopyToAsync(memoryStream);
        var fileBytes = memoryStream.ToArray();

        // Create file entity
        var uploadedFile = new UploadedFile
        {
            FileName = file.FileName,
            ContentType = file.ContentType,
            FileSize = file.Length,
            FileData = fileBytes
        };

        _context.UploadedFiles.Add(uploadedFile);
        await _context.SaveChangesAsync();

        return Ok(new { FileId = uploadedFile.Id, Message = "File uploaded successfully." });
    }
}

Important Tips

  • Increase File Size Limit: By default, ASP.NET Core limits file uploads to 30MB. To increase this, add this to Program.cs:
    builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options =>
    {
        options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50MB
    });
    
  • Run Migrations: Don't forget to create and apply migrations to set up your database tables:
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    
  • Download Files: If you need to retrieve files later, add a GET endpoint that returns the file as a FileContentResult.

内容的提问来源于stack exchange,提问作者Sandeep Gupta

火山引擎 最新活动