【问题标题】:Uploading/Displaying Images in MVC 4在 MVC 4 中上传/显示图像
【发布时间】:2013-04-27 19:09:46
【问题描述】:

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

顺便说一句,为什么没有任何书籍涵盖这个主题?我同时拥有 Pro ASP.NET MVC 4 和 Professional MVC4,但他们没有提及。

【问题讨论】:

  • 如果您关注Pro ASP MVC 4SportsStore Tutorial 会从page 292 开始涵盖此内容
  • 你是对的。我什至没有注意到。正在寻找关于它的章节。谢谢
  • 我知道这是针对 MVC 4 的,但是在寻找 MVC 5 时仍然会出现这个问题。 - 我找到了一个很棒的教程,其中涵盖了上传到数据库和上传到 Mvc 中的文件服务器5 在 MikesDotNetting 上使用 EF 6 mikesdotnetting.com/article/259/…
  • 书中的章节介绍了将图片上传到数据库,大多数人希望将数据库的路径保存到文件夹中。

标签: image asp.net-mvc-4


【解决方案1】:

看看下面的

@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 异步上传文件,请尝试 this article

处理服务器端(用于多次上传)的代码是;

 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 中显示图像。

更新 2

或者,您可以尝试Async File Uploads in MVC 4

【讨论】:

  • 哇。谢谢。我会尝试一下。您能想到的任何资源,我可以阅读以进一步了解该主题吗?我什么都找不到。
  • 在完成file.SaveAs(path) 之后,我该如何从该路径中删除文件?
  • 使用angularjs发送html文件类型图片到服务器端更方便stackoverflow.com/a/26409100/900284
  • @FrankMyatThu 仅使用 Angular 上传图片?这听起来是不是有点奇怪?
  • @DotNetDreamer 我会尽快检查你的网站,因为那里有详细的错误日志记录,目前暴露了一些相当重要的信息......
【解决方案2】:

这是一个简短的教程:

型号:

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

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

查看:

  1. 创建:

    @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. 索引(用于显示):

    @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. 控制器(创建)

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

希望这会有所帮助:)

【讨论】:

  • 哇,非常感谢。如果我想将图像限制为 jpeg 怎么办?
  • @KalaJ 如果您想将上传的图像限制为仅 jpg,您可以添加 accept 属性(Html5 仅适用于 Chrome 和 FF,不适用于 IE)。或者您可以检查控制器filename.LastIndexOf(".") 中的扩展名。希望这会有所帮助
  • @JordyvanEijk,我使用了 accept 属性,但它只适用于 Chrome。它在 FF 或 IE 中不起作用。我需要其他形式的验证。
  • @KalaJ Majbe 你可以用Html5 File Api做点什么如果你需要一些教程Here it is
  • 黑客无需服务器端验证即可上传恶意文件。
【解决方案3】:
        <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];
         }


    }

【讨论】:

  • 那么,如何将“msg”作为图像显示给 img?
  • 您应该删除此答案并恢复您的声誉点数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2013-06-08
  • 2011-11-11
  • 2020-03-02
  • 1970-01-01
  • 1970-01-01
  • 2018-10-10
相关资源
最近更新 更多