将文件从视图上传到.net Core中的控制器



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

在模型中,我有一个类名";电影";具有2个属性:图像-类型为byte[]和图片-类型为IFormFile。

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

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

在我的控制器中,我有一个类似的功能:

public IActionResult NewMovie(Movie movie){...

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

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

我一直无法获取文件的数据。我需要它是byte[]类型,但我会采取任何措施来帮助我。

提前谢谢大家。

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

最新更新