asp.net-mvc - 将文件从视图上传到.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[] 类型,但我会采取任何措施来帮助我。
谢谢大家。
解决方案
您不需要将图像存储在字节数组中,您的模型只需要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
唯一的保存在您的数据库实体中。
推荐阅读
- python - 当我使用 Tensorflow 对不平衡数据的 CNN 应用类权重时,内核死亡
- javascript - Javascript 中的 Murmur3_128
- reactjs - 材质 UI 范围滑块总和 100
- c# - 为什么在使用块和对象初始化程序的情况下不调用 Dispose
- git - 错误:在 Jenkins 管道上获取远程 repo 'origin' 时出错
- python - 从 urls.py 连接 Django .html
- arrays - 在 Swift 中从字典中提取值到数组
- bash - 循环遍历未知数量的具有渐进名称的文件夹
- python - 如何提高我的逻辑回归模型的准确性和精确度?
- java - 如何在 Spring WebClient Retry 中访问响应正文?