如何使用Asp.net MVC6上传带有一些模型数据的文件或图像?例如,我有一个这样的表单;
<form>
<input type="file">
<input type="text" placeholder="Image name...">
<input type="text" placeholder="Image description...">
<input type="submit" value="Submit">
</form>我读了很多关于如何上传的教程,但我没有看到任何像上面这样的数据上传。
另外,有没有像Codeigniter图像操作类一样的图像操作类库,用于调整大小和添加图像水印?(https://codeigniter.com/user_guide/libraries/image_lib.html
发布于 2016-02-14 05:21:33
可以将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 view中,有一个form标记,它的enctype属性设置为"multipart/form-data"
@model CreatePost
<form asp-action="Create" enctype="multipart/form-data">
<input asp-for="ImageCaption"/>
<input asp-for="ImageDescription"/>
<input asp-for="MyImage"/>
<input type="submit"/>
</form>和处理表单张贴的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(model.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,该怎么办?现在您必须修改表中的所有urls!
你应该存储什么?
您应该存储上面生成的唯一文件名(我们在上面使用的uniqueFileName变量)来存储文件名。当您想要显示回图像时,您可以使用此值(文件名)并构建图像的url。
例如,您可以在视图中执行此操作。
@{
var imgFileName = "cats_46df.png";
}
<img src="~/uploads/@imgFileName" alt="my img"/>我只是将图像名称硬编码为imgFileName变量并使用它。但您可以从数据库中读取存储的文件名,并将其设置为视图模型属性并使用该属性。就像这样
<img src="~/uploads/@Model.FileName" alt="my img"/>将图像存储到表的
如果想要将文件以字节数组/varbinary的形式保存到数据库中,可以将IFormFile对象转换为字节数组,如下所示
private byte[] GetByteArrayFromImage(IFormFile file)
{
using (var target = new MemoryStream())
{
file.CopyTo(target);
return target.ToArray();
}
}现在,在http post操作方法中,可以调用此方法从IFormFile生成字节数组,并使用该数组保存到表中。下面的示例尝试使用entity框架保存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");
}发布于 2019-07-30 02:22:49
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>我的行动是
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}发布于 2020-03-16 16:17:31
Fileservice.cs
public class FileService : IFileService
{
private readonly IWebHostEnvironment env;
public FileService(IWebHostEnvironment env)
{
this.env = env;
}
public string Upload(IFormFile file)
{
var uploadDirecotroy = "uploads/";
var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadPath, fileName);
using (var strem = File.Create(filePath))
{
file.CopyTo(strem);
}
return fileName;
}
}IFileService
namespace studentapps.Services
{
public interface IFileService
{
string Upload(IFormFile file);
}
}StudentController
[HttpGet]
public IActionResult Create()
{
var student = new StudentCreateVM();
student.Colleges = dbContext.Colleges.ToList();
return View(student);
}
[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
Student student = new Student()
{
DisplayImage = vm.DisplayImage.FileName,
Name = vm.Name,
Roll_no = vm.Roll_no,
CollegeId = vm.SelectedCollegeId,
};
if (ModelState.IsValid)
{
var fileName = fileService.Upload(vm.DisplayImage);
student.DisplayImage = fileName;
getpath = fileName;
dbContext.Add(student);
dbContext.SaveChanges();
TempData["message"] = "Successfully Added";
}
return RedirectToAction("Index");
}https://stackoverflow.com/questions/35379309
复制相似问题