首页 > 解决方案 > 将文件从视图上传到.net Core中的控制器

问题描述

我正在尝试创建一个带有文件上传的 .net 核心项目。

在模型中,我有一个具有 2 个属性的类名“Movie”:图像 - 字节 [] 类型和图片 - IFormFile 类型。

在视图中,我添加了一个带有输入的表单:

<input asp-for="Picture" type="file" id="image_upload" />

在我的控制器中,我有这样的功能:

public IActionResult NewMovie(Movie movie){...

在传递属性 Image 和 Picture 的电影对象中,始终为 NULL。

我尝试将 asp-for 从 Image 更改为 Picture,将函数更改为 Task 类型,将 IFormFile 添加到函数调用中,但没有任何帮助。

我从来没有能够得到文件的数据。我需要它是 byte[] 类型,但我会采取任何措施来帮助我。

谢谢大家。

标签: asp.net-mvcasp.net-core.net-corefile-upload

解决方案


您不需要将图像存储在字节数组中,您的模型只需要IFormFile这样的:

模型:

[Required(ErrorMessage = "The {0} field is required")]
[Display(Name = "Image")]
[DataType(DataType.Upload)]
public IFormFile Image { get; set; }

控制器:

if (model.Image == null)
   return View(model);

    string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath,"Your upload path");
    string ImagePath = Guid.NewGuid().ToString() + "_" + model.Image.FileName;
    string filePath = Path.Combine(uploadsFolder, ImagePath);
    using (FileStream fs = new FileStream(filePath, FileMode.Create))
    {
        await model.Image.CopyToAsync(fs);
    }

将此添加到您的form标签中:enctype="multipart/form-data"。它对于type="file"提交的输入至关重要。

看法:

<form enctype="multipart/form-data" Other attributes...>
  <div class="custom-file">
   <input asp-for="Model.Image" type="file" class="custom-file-input fileUpload" />
   <label class="custom-file-label fileLabel">Choose file</label>
  </div>
  <input type="submit" value="Submit" />
</form>

最后,您将ImagePath 唯一的保存在您的数据库实体中。


推荐阅读