在MVC 4上传/显示图像 [英] Uploading/Displaying Images in MVC 4
问题描述
任何人都知道的任何一步如何上传使用实体框架数据库/显示图像的步骤教程?我已经签出code片段,但我仍然不是它是如何工作的明确。我没有code,因为除了写一个上传表单,我迷路了。任何(我的意思的话)的帮助是很大的AP preciated。
Anyone know of any step by step tutorials on how to upload/display images from a database using Entity Framework? I've checked out code snippets, but I'm still not clear on how it works. I have no code, because aside from writing an upload form, I'm lost. Any (and I mean any) help is greatly appreciated.
在阿里纳斯,为什么不去任何书籍涉及这个话题?我都临ASP.NET MVC 4与专业MVC4,他们没有提及这一点。
On a sidenote, why don't any books cover this topic? I have both Pro ASP.NET MVC 4 and Professional MVC4, and they make no mention of it.
推荐答案
看看来我的文章的上传图片上也可以使用同样的code描述如下;
您的看法code;
Have a look at to my article on uploading image or you can use the same code described below;
your view code;
@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
您的控制器应具备的行动方法,将接受 HttpPostedFileBase
;
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/images/profile"), pic);
// file is uploaded
file.SaveAs(path);
// save the image path path to the database or you can send image
// directly to database
// in-case if you want to store byte[] ie. for DB
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
// after successfully uploading redirect the user
return RedirectToAction("actionname", "controller name");
}
不过,如果你还想了解更多...尝试的这篇文章。
更新1
如果你要上传使用jQuery与asynchornously文件,然后尝试这篇文章。
In case you want to upload files using jQuery with asynchornously, then try this article.
在code来处理服务器端(多个上传);
the code to handle the server side (for multiple upload) is;
try
{
HttpFileCollection hfc = HttpContext.Current.Request.Files;
string path = "/content/files/contact/";
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
string fileName = "";
if (Request.Browser.Browser == "IE")
{
fileName = Path.GetFileName(hpf.FileName);
}
else
{
fileName = hpf.FileName;
}
string fullPathWithFileName = path + fileName;
hpf.SaveAs(Server.MapPath(fullPathWithFileName));
}
}
}
catch (Exception ex)
{
throw ex;
}
此控制器返回图像名称(在一个javascript调用回),然后你可以用它在DOM来显示图像。
this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.
另外,你可以尝试 异步文件上传MVC 4
Alternatively, you can try Async File Uploads in MVC 4.
这篇关于在MVC 4上传/显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!