如何在asp.net mvc 4中上传图像并显示在同一页面上

san*_*nzy 11 c# image-upload razor asp.net-mvc-4

我使用asp.net mvc4razor语法开发了一个Web应用程序.我需要使用文件上传器上传图像,并在同一页面中显示图像的详细信息.

作为一个例子有一个"file uploader""submit button""contact page"我的应用程序.当我上传一个人的图像和click提交按钮时,它应该在页面的某个位置显示图像,其中的详细信息如图像名称,大小等.

有没有可能实现这一目标的方法?

这是我的控制器类的代码

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是视图的代码

<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" />
Run Code Online (Sandbox Code Playgroud)

但如何在页面上显示?

请帮忙.

Dar*_*rov 18

从控制器操作将上传的文件保存到服务器上后,您可以将URL传递回该文件到视图,以便它可以显示在<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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后强烈键入您的视图,并添加一个<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="" />
}
Run Code Online (Sandbox Code Playgroud)