在.NET 6中,可以使用以下方法实现图片上传功能:

  1. 在ASP.NET Core项目中创建一个控制器,用于处理图片上传的请求。
[ApiController]
[Route("api/[controller]")]
public class ImagesController : ControllerBase
{
    [HttpPost]
    public IActionResult UploadImage(IFormFile file)
    {
        // 检查文件是否为空
        if (file == null || file.Length == 0)
        {
            return BadRequest("文件不能为空");
        }

        // 检查文件类型
        if (!IsImageFile(file))
        {
            return BadRequest("文件类型不正确");
        }

        // 生成唯一的文件名
        string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);

        // 保存文件到服务器
        string filePath = Path.Combine("uploads", fileName);
        using (FileStream stream = new FileStream(filePath, FileMode.Create))
        {
            file.CopyTo(stream);
        }

        // 返回文件路径
        return Ok(filePath);
    }

    private bool IsImageFile(IFormFile file)
    {
        // 根据需要检查文件类型的条件
        string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif" };
        string fileExtension = Path.GetExtension(file.FileName).ToLower();

        return allowedExtensions.Contains(fileExtension);
    }
}
  1. 在ASP.NET Core项目的Startup.cs文件的ConfigureServices方法中配置文件上传相关的服务。
public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddControllers();
    services.AddCors(); // 添加跨域支持

    // 配置文件上传的最大限制
    services.Configure<IISServerOptions>(options =>
    {
        options.MaxRequestBodySize = int.MaxValue;
    });
}
  1. 在前端页面中,使用FormData对象将文件上传到服务器。
function uploadImage(file) {
  let formData = new FormData();
  formData.append("file", file);

  fetch("/api/images", {
      method: "POST",
      body: formData
  })
  .then(response => response.json())
  .then(data => {
      console.log("上传成功,文件路径:" + data);
  })
  .catch(error => {
      console.error("上传失败:" + error);
  });
}

// 使用示例
let inputFile = document.getElementById("fileInput");
inputFile.addEventListener("change", function() {
  let file = inputFile.files[0];
  uploadImage(file);
});

上述代码中,将文件上传到/api/images路由,通过FormData对象将文件作为表单数据发送到服务器。服务器接收到文件后,进行简单的验证(文件不能为空、文件类型正确),然后保存文件到服务器的指定目录。最后,返回文件路径给前端

net6 图片上传功能实现

原文地址: http://www.cveoy.top/t/topic/iYzs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录