【问题标题】:Upload File From View to Controller in .net Core将文件从视图上传到.net Core中的控制器
【发布时间】:2021-01-10 20:55:45
【问题描述】:

我正在尝试创建一个带有文件上传的 .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-mvc asp.net-core .net-core file-upload


    【解决方案1】:

    您不需要将图像存储在字节数组中,您的模型只需要像这样的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 only 保存在您的数据库实体中。

    【讨论】:

      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2021-02-21
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多