在 MVC 4 中上传/显示图像
有人知道有关如何使用实体框架从数据库上传/显示图像的分步教程吗?我已经检查了代码片段,但我仍然不清楚它是如何工作的.我没有代码,因为除了编写上传表单之外,我迷路了.非常感谢任何(我的意思是任何)帮助.
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.
顺便说一句,为什么没有任何书籍涉及这个主题?我有 Pro ASP.NET MVC 4 和 Professional 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.
看看下面的
@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
的 action 方法;
your controller should have action method which would accept 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 异步上传文件,请尝试这篇文章.
In case you want to upload files using jQuery with asynchornously, then try this article.
处理服务器端(用于多次上传)的代码是;
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.