Asp.net mvc 4 如何使用mvc4从实体框架上传和检索图像
我是asp.NETMVC新手。我需要关于如何使用mvc4从实体框架上传和检索图像的帮助。请给我逐步的信息 这是我的模型Asp.net mvc 4 如何使用mvc4从实体框架上传和检索图像,asp.net-mvc-4,Asp.net Mvc 4,我是asp.NETMVC新手。我需要关于如何使用mvc4从实体框架上传和检索图像的帮助。请给我逐步的信息 这是我的模型 BUser public byte[] Image { get; set; } 控制器 public ActionResult FileUpload(HttpPostedFileBase file) { if (file != null) { HMSEntities2 db = new HMSEntities2
BUser
public byte[] Image { get; set; }
控制器
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
HMSEntities2 db = new HMSEntities2();
string ImageName = System.IO.Path.GetFileName(file.FileName);
byte[] y = System.Text.Encoding.UTF8.GetBytes(ImageName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
// save image in folder
file.SaveAs(physicalPath);
//save new record in database
User newRecord = new User();
newRecord.Image = y;
db.Users.Add(newRecord);
db.SaveChanges();
}
//Display records
return RedirectToAction("Display","BPatient");
}
public ActionResult Display()
{
return View();
}
编辑视图
@using (Html.BeginForm("FileUpload","BPatient", FormMethod.Post, new{@class = "form-horizontal role='form' container-fluid enctype='multipart/form-data' " }))
<div class="form-group">
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
</div>
@使用(Html.BeginForm(“FileUpload”、“BPatient”、FormMethod.Post、新的{@class=“form horizontal role='form'container fluid enctype='multipart/form data''))
首先,我们不要将图像存储在数据库中,而是存储对图像的引用
公共类总线{
公共int Id{get;set;}
公共字符串ImagePath{get;set;}
}
现在,在我们的操作中,让我们发布图像,将其保存在相关目录中,比如/Images/UserImages,然后在我们的类中存储对该图像的引用
因此,首先是ActionResult,它引用了我们将要使用的ImageService:
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file.ContentLength > 0 && _imageService.IsValidImageType(file.ContentType))
{
const string imagePath = "/Images/UserImages/";
string uploadedImage = _imageService.UploadImage(file, Server.MapPath(imagePath));
string uploadedPath = string.Format("{0}{1}",imagePath, uploadedImage);
if (uploadedPath.Contains("Fail"))
{
return RedirectToAction("Failed", "BPatient");
}
var bUser = new BUser() {Image = uploadedPath};
//Save to DB
}
return RedirectToAction("Display", "BPatient");
}
事实上,我们不想让控制器的动作膨胀这么多,但是我试图让它与您已经拥有的类似,所以它不是一个完全重写。现在,这里是我们的服务代码,它将上传我们的图像,并检查其是否为有效的图像类型
//Extract this to a service or helper
private readonly string[] _validFileTypes = new[] { "image/jpeg", "image/pjpeg", "image/png", "image/gif" };
public string UploadImage(HttpPostedFileBase file, string path)
{
if (file != null)
{
try
{
string fileName = System.IO.Path.GetFileName(file.FileName);
if (string.IsNullOrEmpty(fileName))
{
return "Fail";
}
if (!IsValidImageType(file.ContentType))
{
return "Fail";
}
}
catch (Exception ex)
{
return "Fail";
}
string extensionlessName = NameWithoutExtesion(file.FileName);
string randomName = System.IO.Path.GetRandomFileName();
string pathMain = string.Format("{0}{1}{2}{3}", path, extensionlessName, randomName, System.IO.Path.GetFileName(Path.GetExtension(file.FileName)));
try
{
file.SaveAs(pathMain);
return string.Format("{0}{1}{2}", extensionlessName, randomName, System.IO.Path.GetFileName(Path.GetExtension(file.FileName)));
}
catch (Exception ex)
{
return "Fail";
}
}
return "Fail";
}
这里是该服务的两个小方法,它们只会减少上传图像的总体大小
public bool IsValidImageType(string fileType)
{
if (string.IsNullOrEmpty(fileType))
{
return false;
}
if (!_validFileTypes.Contains(fileType))
{
return false;
}
return true;
}
public string NameWithoutExtesion(string name)
{
if (!name.Contains("."))
{
return name;
}
int index = name.LastIndexOf('.');
string newName = name.Substring(0, index);
return newName;
}
这就是我所能说的有效解决方案。当然,它将需要一些更多的工作插入到数据库中,但是我已经留下了一个评论,让你把代码放进去
虽然该服务将直接从副本粘贴工作,但该操作将需要您的一点工作。一旦一切都连接好,我建议你尝试一下,看看有什么不同的做法。你能告诉我们你尝试了什么吗?请看我的更新问题,我正在遵循本教程。.每当我试图上传pic时,它给了我一个错误…即(HttpPostedFileBase文件)为空你正在使用(…){html here}围绕着表单使用
@using(…)
?很抱歉延迟回复@Glitch100…但是如果(file.ContentLength>0&&&u imageService.IsValidImageType(file.ContentType))和字符串UploadeImage=\u imageService.UploadeImage(file,Server.MapPath(imagePath)),我在这里得到一个错误
erro是当前上下文中不存在的名称“_imageService”,这是因为我说过将所有这些方法添加到名为imageService的类中,然后声明一个实例以供使用