在 MVC 4中上传/显示图像

有人知道如何使用实体框架从数据库上传/显示图像的分步教程吗?我已经检查了代码片段,但我仍然不清楚它是如何工作的。我没有代码,因为除了写一个上传表单,我迷路了。任何(我的意思是任何)帮助都是非常感谢的。

顺便说一句,为什么没有一本书涉及这个主题?我有专业的 ASP.NET MVC4和专业的 MVC4,他们没有提到它。

292704 次浏览

Have a look at the following

@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" />
}

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");
}

Update 1

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;
}

this control also return image name (in a javascript call back) which then you can use it to display image in the DOM.

UPDATE 2

Alternatively, you can try Async File Uploads in MVC 4.

Here is a short tutorial:

Model:

namespace ImageUploadApp.Models
{
using System;
using System.Collections.Generic;


public partial class Image
{
public int ID { get; set; }
public string ImagePath { get; set; }
}
}

View:

  1. Create:

    @model ImageUploadApp.Models.Image
    @{
    ViewBag.Title = "Create";
    }
    <h2>Create</h2>
    @using (Html.BeginForm("Create", "Image", null, FormMethod.Post,
    new { enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
    <legend>Image</legend>
    <div class="editor-label">
    @Html.LabelFor(model => model.ImagePath)
    </div>
    <div class="editor-field">
    <input id="ImagePath" title="Upload a product image"
    type="file" name="file" />
    </div>
    <p><input type="submit" value="Create" /></p>
    </fieldset>
    }
    <div>
    @Html.ActionLink("Back to List", "Index")
    </div>
    @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    }
    
  2. Index (for display):

    @model IEnumerable<ImageUploadApp.Models.Image>
    
    
    @{
    ViewBag.Title = "Index";
    }
    
    
    <h2>Index</h2>
    
    
    <p>
    @Html.ActionLink("Create New", "Create")
    </p>
    <table>
    <tr>
    <th>
    @Html.DisplayNameFor(model => model.ImagePath)
    </th>
    </tr>
    
    
    @foreach (var item in Model) {
    <tr>
    <td>
    @Html.DisplayFor(modelItem => item.ImagePath)
    </td>
    <td>
    @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
    @Html.ActionLink("Details", "Details", new { id=item.ID }) |
    @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
    </td>
    </tr>
    }
    
    
    </table>
    
  3. Controller (Create)

    public ActionResult Create(Image img, HttpPostedFileBase file)
    {
    if (ModelState.IsValid)
    {
    if (file != null)
    {
    file.SaveAs(HttpContext.Server.MapPath("~/Images/")
    + file.FileName);
    img.ImagePath = file.FileName;
    }
    db.Image.Add(img);
    db.SaveChanges();
    return RedirectToAction("Index");
    }
    return View(img);
    }
    

Hope this will help :)

        <input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;


var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);


$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {


alert(msg);


},
error: function (error) {
alert("errror");
}
});


});


[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}




}