how to view image on mvc website instantly after u

2019-12-16 19:51发布

问题:


I have website with form I'am uploading image from using Html.BeginForm() through the controller. Uploaded image saves correctly (i see it in folder) but I can't see it on website. To do so I have to reload entire webbrowser.
How can I make image showing on my website after uploading? Website shows this image few times, on different views, always by <img scr="imagePatch"/>. New image just saves itself with the same name as previous one, replacing it.

回答1:

there are many ways to do this you can use html file api inside your form.

   $(document).ready(function(){
    // render the image in our view
    function renderImage(input,file) {

      // generate a new FileReader object
      var reader = new FileReader();

      // inject an image with the src url
      reader.onload = function(event) {
        the_url = event.target.result;
        $('.img-preview__').remove();
        $(input).after("<img class='img-preview__' src='" + the_url + "' />")
      }

      // when the file is read it triggers the onload event above.
      reader.readAsDataURL(file);
    }

    // handle input changes  ... you can change selector
    $("#the-file-input").change(function(event) {
        // grab the first image in the FileList object and pass it to the function
        renderImage(event.target,this.files[0]);
    }); 
});

this will work nice . either you can make your image preview look like better. for image preview element use this css code

 img.img-preview__ {
    width: 120px;
    border: 3px solid #ddd;
    border-radius: 3px;
    display: inline-block;
}

for example

<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post, 
                              new { enctype = "multipart/form-data" })) {

    <fieldset>
        <legend>Image</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ImagePath)
        </div>
        <div class="editor-field">
            <input id="the-file-input" title="Upload a product image" 
                                  type="file" name="file" />
        </div>
        <p><input type="submit" value="Create" /></p>
    </fieldset>
}

I hope this help