MVC 4 图片的上传及显示
1 首先我们看一下如何上传
1.1 view
上传页面:
1: @using (Html.BeginForm("Create", "Achievement", FormMethod.Post, new { enctype = "multipart/form-data" }))
2: {
3: <div class="editor-label">
4: @Html.LabelFor(model => model.Pictures)
5: </div>
6: <div class="editor-field">
7: <div><input type="file" name="Image" /></div>
8: </div>
9: }
这里需要注意的是BeginForm方法的参数
1.2 control
1: public ActionResult Create(Achivement achieve, HttpPostedFileBase image)
2: {
3: try
4: {
5:
6: if (image != null && image.ContentLength > 0)
7: {
8: string fileName = DateTime.Now.ToString("yyyyMMdd") + "-" + Path.GetFileName(image.FileName);
9: string filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
10: image.SaveAs(filePath);
11: achieve.Pictures = "~/Images/" + fileName ;
12: }
13: m_achivementService.Create(achieve);
14: return RedirectToAction("Index");
15: }
16: catch
17: {
18: return View();
19: }
20: }
现在图片已上传到Images目录下,注意这里Pictures字段存的图片路径一定要带上“~”。
2 现在我们来看下如何显示
2.1 view
1: @using (Html.BeginForm("Edit", "Achievement", FormMethod.Post, new { enctype = "multipart/form-data" }))
2: {
3: <div class="editor-label">
4: @Html.LabelFor(model => model.Pictures)
5: </div>
6: <div class="editor-field">
7: @*@Html.EditorFor(model => model.Pictures)
8: @Html.ValidationMessageFor(model => model.Pictures)*@
9: <div><input type="file" name="Image" /></div>
10: <div>
11: @if (string.IsNullOrEmpty(Model.Pictures))
12: {
13: @:None
14: }
15: else
16: {
17: <img width="150" height="150" src="@Url.Content(Model.Pictures)" alt="images" />
18: }
19: </div>
20: </div>
21: }
这里需要注意的是src的地方,不能直接写上Model.Pictures,前面要加上@Url.Content, 不然显示的是c:/images/123.png, 图片不能正常显示。
2.2 control
跟create一样的操作, 此处省略。
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?