How to upload a image and display on same page in

2019-03-13 06:33发布

问题:

i have developed a web application using asp.net mvc4 and razor syntax. i need to upload an image using file uploader and display in the same page with details of the image.

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 click the submit button, it should display the image somewhere in the page with its details like image name, size like that.

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.

回答1:

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:

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:

@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="" />
}


回答2:

in HTML:

<input type='file' onchange="readURL(this);" />

Javascript/JQuery through the 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 input is the <input type="file"> element if you use AjaxToolKit AsyncFileUpload, you can get the input using: fileUploadElement.get_inputFile()

Please refere to: how to preview a image before and after upload?



回答3:

To display uploaded image on page, you will have to save the image somewhere, then reference corresponding URL in the <img> tag.

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 Img the relative URL would be ~/Img/imagename).

If you save it to the database, you'll have to provide a separate action method or HttpHandler to get it.



回答4:

So here's the typical flow for something like this.

  1. You start out on the Index action which you can see the fileupload control.
  2. The fileupload is in a form that will submit to your FileUpload action.
  3. Inside your FileUpload action you do your thing and at the end you 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.

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.