我已经使用 asp.net mvc4 和 razor 语法开发了一个网络应用程序。 我需要使用文件 uploader 上传一张图片,并在同一页面上显示图片的详细信息。
例如,在我的应用程序的“联系页面”
中有一个“文件 uploader ”
和“提交按钮”
。当我上传一个人的图像并单击
提交按钮时,它应该在页面的某处显示图像及其详细信息,如图像名称、尺寸等。
有什么办法可以实现吗?
这是我的 Controller 类的代码
public class FileUploadController : Controller
{
//
// GET: /FileUpload/
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("~/Img/"),
Path.GetFileName(uploadFile.FileName));
}
return View();
}
}
下面是查看代码
<h2>FileUpload</h2>
@(Html.BeginForm("FileUpload", "FileUpload",FormMethod.Post, new { enctype = "multipart/form-data" }))
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
但是如何在页面上显示呢?
请帮忙。
最佳答案
一旦您通过 Controller 操作将上传的文件保存在服务器上,您就可以将该文件的 url 传回 View ,以便它可以显示在 <img>
中。标签:
public class FileUploadController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult FileUpload()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string relativePath = "~/img/" + Path.GetFileName(uploadFile.FileName);
string physicalPath = Server.MapPath(relativePath);
uploadFile.SaveAs(physicalPath);
return View((object)relativePath);
}
return View();
}
}
然后使您的 View 强类型化并添加一个 <img>
如果模型不为空,将显示图像的标签:
@model string
<h2>FileUpload</h2>
@using (Html.BeginForm("FileUpload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" })
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
}
@if (!string.IsNullOrEmpty(Model))
{
<img src="@Url.Content(Model)" alt="" />
}
关于c# - 如何在asp.net mvc 4中上传图片并显示在同一页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17061216/