asp.net-mvc - 以表单上传图像并在 MVC 4 上显示

标签 asp.net-mvc


存储用户上传的图像然后将其显示在我的网站中的最佳方式是什么?

  1. 将其作为二进制存储在数据库中。那我该如何用`img`来显示它呢?
    我想我应该以某种方式将其写入目录,然后将其地址作为“img”的“src”属性传递。
  2. 我可以将其存储在网络服务器中的某个位置,将图像的地址存储在数据库中。那么我应该简单地在“src”属性中指定数据库中的地址。
  3. 其他方式?!

我认为第二种方式更方便。
还有一个问题!
在这两种情况下,我如何以 html 形式上传这些图像? @Html没有类似 @Html.FileFor(...) 的东西以及如何获取 <input type='file'/> 的数据在我的行动中?
我很感激任何建议。

最佳答案

in my opinion the second way is more convenient.

我也这么认为。

In both case How Can I upload this images in html form?

非常简单。与往常一样,在 ASP.NET MVC 应用程序中,您首先要设计 View 模型:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

那么您可以拥有一个具有 2 个操作的 Controller (一个呈现 View ,另一个处理文件上传):

public class HomeController: Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // the user didn't upload any file =>
            // render the same view again in order to display the error message
            return View(model);
        }

        // at this stage the model is valid => 
        // you could handle the file upload here

        // let's generate a filename to store the file on the server
        var fileName = Guid.NewGuid().ToString() + Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
        // store the uploaded file on the file system
        file.SaveAs(path);

        // TODO: now you could store the path in your database

        // and finally return some ActionResult
        // to inform the user that the upload process was successful
        return Content("Thanks for uploading. Your file has been successfully stored on our server");
    }
}

最后您将拥有一个相应的强类型 View ,它将包含上传文件的表单:

@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        @Html.LabelFor(x => x.File)
        @Html.TextBoxFor(x => x.File, new { type = "file" })
        @Html.ValidationMessageFor(x => x.File)
    </div>
    <button type="sybmit">Upload</button>
}

此外,我建议您阅读 Phil Haack's blog post这说明了 ASP.NET MVC 中文件上传的工作原理。

关于asp.net-mvc - 以表单上传图像并在 MVC 4 上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675185/

相关文章:

asp.net-mvc - 如何在 DropDownListFor 的扩展中添加额外的 htmlattributes

html - 为什么 .NET Razor 中的这些 HTML 元素有由换行引起的额外间距?

asp.net-mvc - 如何使用从源代码而不是 GAC 构建的 ASP.NET MVC?

javascript - 在 HIGHCHARTS 中无法设置仪表中的最大点

MySqlClient : SaveChanges in ASP. NET 不更新数据库表

c# - 为什么 MVC 5 不调用我的 VirtualPathProvider 类的 GetFile 方法?

asp.net-mvc - 使用 Azure AD 和 ADAL 3 的 MVC 应用程序 - 身份验证 Cookie 在 1 小时后过期

asp.net-mvc - 在MVC Controller 构造函数中获取主机名

asp.net - Html.RouteLink 到 Web API 路由 - 可能吗?

c# - 如何将编码标签呈现为正确的 HTML,而不是文本?