如何在asp.net核心上传文件?

如何使用Asp.net MVC 6上传文件或图像以及一些模型数据? 例如,我有一个这样的表格;

我阅读了很多关于如何上传的教程,但我没有看到任何上传的内容与上面的表格一样。

另外,是否有任何用于重新resize和图像水印的图像处理库,与Codeigniter图像处理类相同? ( https://codeigniter.com/user_guide/libraries/image_lib.html

您可以向视图模型添加IFormFile类型的新属性

 public class CreatePost { public string ImageCaption { set;get; } public string ImageDescription { set;get; } public IFormFile MyImage { set; get; } } 

在您的GET操作方法中,我们将创建此视图模型的对象并发送到视图。

 public IActionResult Create() { return View(new CreatePost()); } 

现在,在我们的视图模型中强类型的Create视图中,有一个form标签,其enctype属性设置为"multipart/form-data"

 @model CreatePost 

和你的HttpPost动作来处理表单发布

 [HttpPost] public IActionResult Create(CreatePost model) { var img = model.MyImage; var imgCaption = model.ImageCaption; //Getting file meta data var fileName = Path.GetFileName(model.MyImage.FileName); var contentType = model.MyImage.ContentType; // do something with the above data // to do : return something } 

如果要将文件上载到应用程序中的某个目录,则应使用IHostingEnvironment获取webroot路径。 这是一个工作样本。

 public class HomeController : Controller { private readonly IHostingEnvironment hostingEnvironment; public HomeController(IHostingEnvironment environment) { hostingEnvironment = environment; } [HttpPost] public IActionResult Create(CreatePost model) { // do other validations on your model as needed if (model.MyImage != null) { var uniqueFileName = GetUniqueFileName(vm.MyImage.FileName); var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads"); var filePath = Path.Combine(uploads,uniqueFileName); model.MyImage.CopyTo(new FileStream(filePath, FileMode.Create)); //to do : Save uniqueFileName to your db table } // to do : Return something return RedirectToAction("Index","Home"); } private string GetUniqueFileName(string fileName) { fileName = Path.GetFileName(fileName); return Path.GetFileNameWithoutExtension(fileName) + "_" + Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName); } } 

这将使用Guids生成的随机文件名将文件保存到应用程序的wwwwroot目录中的uploads文件夹中(以防止覆盖具有相同名称的文件)

这里我们使用一个非常简单的GetUniqueName方法,它将guid中的4个字符添加到文件名的末尾,使其有点独特。 您可以根据需要更新方法以使其更加复杂。

您是否应该将完整的URL存储到数据库中的上传图像?

不。不要将完整的URL存储到数据库中的图像中。 如果明天您的公司决定将您的公司/产品名称从www.thefacebook.com更改为www.facebook.com怎么办? 现在你必须修复表中的所有url!

你应该存储什么?

您应该存储上面生成的唯一文件名( 我们上面使用的uniqueFileName )来存储文件名。 如果要显示图像,可以使用此值(文件名)并为图像构建URL。

例如,您可以在视图中执行此操作。

 @{ var imgFileName = "cats_46df.png"; } my img 

我只是将图像名称硬编码为imgFileName变量并使用它。 但是,您可以从数据库中读取存储的文件名,并将其设置为视图模型属性并使用它。 就像是

 my img 

将图像存储到表格中

如果要将文件保存为bytearray / varbinary到数据库,可以将IFormFile对象转换为像这样的字节数组

 private byte[] GetByteArrayFromImage(IFormFile file) { using (var target = new MemoryStream()) { file.CopyTo(target); return target.ToArray(); } } 

现在在http post动作方法中,您可以调用此方法从IFormFile生成字节数组,并使用它保存到您的表中。 下面的示例尝试使用entity framework保存Post实体对象。

 [HttpPost] public IActionResult Create(CreatePost model) { //Create an object of your entity class and map property values var post=new Post() { ImageCaption = model.ImageCaption }; if (model.MyImage != null) { post.Image = GetByteArrayFromImage(model.MyImage); } _context.Posts.Add(post); _context.SaveChanges(); return RedirectToAction("Index","Home"); } 

你可以尝试下面的代码

1-模型或视图模型

 public class UploadImage { public string ImageFile { get; set; } public string ImageName { get; set; } public string ImageDescription { get; set; } } 

2-查看页面

 

3-控制器

  public class Image { private IHostingEnvironment _hostingEnv; public Image(IHostingEnvironment hostingEnv) { _hostingEnv = hostingEnv; } [HttpPost] public IActionResult UploadImage(UploadImage model, IFormFile ImageFile) { if (ModelState.IsValid) { var filename = ContentDispositionHeaderValue.Parse(ImageFile.ContentDisposition).FileName.Trim('"'); var targetDirectory = Path.Combine(_hostingEnv.WebRootPath, string.Format("Common\\Images\\")); var savePath = Path.Combine(targetDirectory, filename); ImageFile.CopyTo(new FileStream(savePath, FileMode.Create)); model.ImageFile = filename; _imageUploadAppService.UserCreate(model); } } }