3

I've checked this question that treats the same issue but it didn't worked for me . I actually upload an image but when I click on the load button in order to display the image it redirect me to another page but I want to show it in my current page . Do you have an idea of how to resolve this problem ? Here is my controller

[HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Content"), fileName);
                file.SaveAs(path);


                return File(path, "image/jpeg");

    }

and in my view

@using(Html.BeginForm("Index","Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
    {
        <input style="margin-left:40px;cursor:pointer;" type="file" name="file" id="upload1" />
        <input type="submit" style="margin-left:40px;cursor:pointer;" id="load1" value="Upload" />

        <img src="myimage" alt="Logo" />


      }
Community
  • 1
  • 1
ItShine
  • 349
  • 1
  • 4
  • 22
  • Rather than returning a file, why don't you redirect to the `HttpGet` version of `Index()`? – 48klocs May 09 '14 at 15:26
  • Another option would be to create a seperate method that accepts the file, call it via ajax, and just return the path to the image so you can insert an img tag – tympaniplayer May 09 '14 at 15:27

2 Answers2

0

You need to submit your form by ajax so that the user isn't taken to another page. Submitting a file through ajax is tricky so you'll probably want to use the jQuery Form Plugin or something like it. In your action method you need to return the URL of the uploaded image instead of the actual image bytes. You'll then assign this URL to the source of the image tag with javascript. Also, I don't think you can access the uploaded file as a parameter in your action method like you have above. You'll probably need to get the file from the Request.Files collection.

Jason Nesbitt
  • 730
  • 1
  • 6
  • 15
0

To only way to achieve a good user experience with file or image upload is to do it Ajax style. Yet the details are very tricky. For that reason I strongly suggest to the jQuery File Upload plugin, which handles all the nifty details.

You hardly need to change anything in your MVC code. A complete example of how to use it with ASP.NET can be found in ASP.NET MVC: Simple example of ajax file upload using jQuery.

Torino
  • 588
  • 2
  • 9