带图像的模型 - 如何上传/显示 [英] Model with images - how to Upload/Display

查看:128
本文介绍了带图像的模型 - 如何上传/显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我开始学习ASP.NET MVC 4,我正在努力学习如何将图像/位图对象添加到我拥有的模型中,让用户从桌面上选择一个图像进行上传,这样我就可以将其保存到我的数据库稍后会在我的网站上显示。

Recently I started learning ASP.NET MVC 4 and I am struggling with how to add an image/bitmap object to a Model that I have and let the user pick an image from his desktop to upload, so I could save it to my database for displaying it later on my website.

在我的培训网站上我正在做吉他销售网站,
我有一个有Id的模型,标题,品牌和价格。
我所做的就是创建一个索引页面来显示来自数据库的所有GutiarDataContext和一个创建页面,但是我想创建一个选项来选择一个图像并将其保存到数据库中然后显示它在索引视图中。

In my training website i am doing a guitar selling website , I got a model that has Id , title , brand and price. All i did was creating a index page to show all the GutiarDataContext from the database and a create page , but i want to make an option for the creation to choose an image and save it to the database and off course displaying it in the Index view.

我已经在互联网和这里找到了一些答案,但我真的不明白他们在那里解释的是什么,所以如果有人可以给我一个示例和解释它是如何工作的,这将是非常棒的!

I already went through some answers on the internet and here but I couldn't really understand what they were trying to explain there, so if someone could show me an example and explanation on how it works, that would be awesome!

谢谢:)

推荐答案

用于在数据库中存储图像:

For Storing images in database :

在Asp.Net MVC中,我们必须使用 HttpPostedFileBase 用于上传的文件,如下所示: -

In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-

控制器:

[HttpPost]
public ActionResult Upload(UploadViewModel model, HttpPostedFileBase file)
{
 if (file != null)
 {
    int byteCount = file.ContentLength;   <---Your file Size or Length
    .............
    .............
 }
}

查看:

@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  <input type="file" name="file" />
  <input type="submit" value="OK" />
}

用于显示来自数据库的图像(我在这里假设一个例子)

For displaying images from database(i m taking a hypothetical example here)

<img height="80" width="140" class="imgThumb" src="@Url.Action("LoadImg", "Image", new { id = m.ImgId })" alt="Loading..." />

public ActionResult LoadImg(int id)
{
byte[] image = null;
tblImage img = en.tblImages.FirstOrDefault(i => i.ImgId == id);
image = (byte[])img.ImgSrc;
return File(image, "image/png");
}

这篇关于带图像的模型 - 如何上传/显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆