asp.net-mvc – 以表格形式上传图片并在MVC 4上显示
|
存储用户上传的图像然后在我的网站上显示的最佳方式是什么? >将其作为二进制文件存储在DB中.那怎么用`img`来展示呢? 在我看来,第二种方式更方便. 解决方法
是的,在我看来也是如此.
满容易.与ASP.NET MVC应用程序一样,您首先要设计一个视图模型: public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
然后你可以让一个控制器有2个动作(一个渲染视图,另一个渲染文件上传): 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");
}
}
最后你将有一个相应的强类型视图,它将与表单相关联以上传文件: @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>
}
另外我建议你阅读 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net – 如果在Application_Start中抛出未处理的异常会发
- asp.net-mvc – 如何将整数列表传递给MVC操作?
- asp.net – 如何设置MVC应用程序的默认页面?
- NHibernate中关于Inverse的理解和使用
- asp.net-mvc – 在asp.net mvc中,单个项目与多个项目实现的
- asp.net – 我应该使用WebMatrix构建一个真实世界的网站吗?
- asp.net – IIS如何知道它是服务于一个网站还是一个Web应用
- asp.net-mvc – 在哪里得到的Microsoft.Web.Mvc.dll
- asp.net-mvc – 哪一层应该构建一个View Model?
- asp.net-mvc-2 – ASP.MVC 2 RTM ModelState Id属性的错误
- asp.net – 为什么Request.IsSecureConnection返
- asp.net-mvc – 在Owin Identity和Asp.Net MVC中
- 如何在ASP.NET表中创建thead和tbody?
- asp.net-mvc – MVC4 Razor – @ Html.DisplayFo
- asp.net-mvc – ASP.net Web API和System.Net.Ht
- asp.net-core – 从与xproj相同的解决方案引用cs
- asp.net-mvc – 接受逗号和点作为小数分隔符[重复
- asp.net – 用于Basic或Windows身份验证的无限重
- asp.net-core – Netcore 2.1.1版本导致应用程序
- asp.net-mvc – 对ASP.NET MVC应用程序使用.resx
