C# 如何在asp.net mvc 4中上传图像并显示在同一页面上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17061216/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to upload a image and display on same page in asp.net mvc 4
提问by sanzy
i have developed a web application using asp.net mvc4and razorsyntax. i need to upload an image using file uploader and display in the same page with details of the image.
我已经使用 asp.net mvc4和razor语法开发了一个 Web 应用程序。我需要使用文件上传器上传图像并在同一页面中显示图像的详细信息。
as an example there's a "file uploader"and "submit button"in "contact page"of my application. when i upload an image of a person and clickthe submit button, it should display the image somewhere in the page with its details like image name, size like that. 
例如,我的应用程序中有一个"file uploader"and "submit button"in "contact page"。当我上传一个人的图像和click提交按钮时,它应该在页面的某处显示图像及其详细信息,如图像名称、大小等。
is there any possible way to achieve that?
有什么可能的方法来实现吗?
here is the code for my controller class
这是我的控制器类的代码
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();
        }
    }
and here is the code for 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" />
but how to display on page?
但是如何在页面上显示呢?
please help.
请帮忙。
采纳答案by Darin Dimitrov
Once you save the uploaded file on the server from your controller action you could pass back the url to this file to the view so that it can be displayed in an <img>tag:
一旦您从控制器操作将上传的文件保存到服务器上,您就可以将该文件的 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();
    }
}
Then make your view strongly typed and add an <img>tag that will display the image if the model is not empty:
然后让你的视图强类型化并添加一个<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="" />
}
回答by The Muffin Man
So here's the typical flow for something like this.
所以这里是这样的典型流程。
- You start out on the 
Indexaction which you can see the fileupload control. - The fileupload is in a form that will submit to your 
FileUploadaction. - Inside your 
FileUploadaction you do your thing and at the end youreturn RedirectToAction("Index"); 
- 您从
Index可以看到文件上传控件的操作开始。 - 文件上传的形式将提交给您的
FileUpload操作。 - 在你的
FileUpload行动中你做你的事,最后你return RedirectToAction("Index"); 
Now obviously there's more to do. You need to save that file somewhere, let's say in a directory called UploadStuff.
现在显然还有更多工作要做。您需要将该文件保存在某个地方,比如说在一个名为UploadStuff.
Within your index action you will read that directory for your file.
在您的索引操作中,您将为您的文件读取该目录。
Again this is to get you going. In the real world you're storing a reference to this file in say a database and querying that database based off of some unique identifier such as a userId or a productId to figure out which uploaded items get shown on the index view.
这也是为了让你前进。在现实世界中,您将对该文件的引用存储在一个数据库中,并根据一些唯一标识符(例如 userId 或 productId)查询该数据库,以确定哪些上传的项目显示在索引视图中。
回答by Andrey Shchekin
To display uploaded image on page, you will have to save the image somewhere, then reference corresponding URL in the <img>tag.
要在页面上显示上传的图像,您必须将图像保存在某处,然后在<img>标签中引用相应的 URL 。
If you save it on disk within the website location, you can reference it by the URL that corresponds to the save location (so if you save it to Imgthe relative URL would be ~/Img/imagename).
如果将其保存在网站位置内的磁盘上,则可以通过与保存位置对应的 URL 来引用它(因此,如果将其保存到Img相对 URL 中,则为~/Img/imagename)。
If you save it to the database, you'll have to provide a separate action method or HttpHandlerto get it.
如果将其保存到数据库中,则必须提供单独的操作方法或HttpHandler获取它。
回答by Muhammad Omar ElShourbagy
in HTML:
在 HTML 中:
<input type='file' onchange="readURL(this);" />
Javascript/JQuery through the Type FileReader
Javascript/JQuery 通过 Type FileReader
if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
where inputis the <input type="file">element
if you use AjaxToolKit AsyncFileUpload, you can get the input using: fileUploadElement.get_inputFile()
这里input是<input type="file">元素,如果你使用AjaxToolKit AsyncFileUpload,你可以使用获得输入:fileUploadElement.get_inputFile()
Please refere to: how to preview a image before and after upload?
请参考:如何预览图片上传前后?

