Live2D 看板娘 / Demo

ASP.NET Core 文件上传

以下是将上传的图片保存在本地的示例代码:

1、在前端,使用HTML表单元素和POST方法将文件上传到后端:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="image" />
    <button type="submit">Upload</button>
</form>

2、在后端,使用IFormFile接口和FileStream类将上传的文件保存到本地磁盘上:

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

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

    return Ok();
}

 

posted @ 2023-03-09 22:28  KysonDu  阅读(180)  评论(0编辑  收藏  举报