2016-11-02 32 views
-1


我有网站与形式我上传图像使用Html.BeginForm()通过控制器。上传的图像正确保存(我在文件夹中看到它),但我无法在网站上看到它。为此,我必须重新加载整个网页浏览器。
如何在上传后在我的网站上显示图像?网站通过不同的视图几次显示此图片,总是由<img scr="imagePatch"/>。新图像只保存与前一个图像相同的名称,替换它。如何在上传后立即在mvc网站上查看图像?

+0

使用jQuery您可以预览图像之前也上载服务器参考HTTP:// codepedia。信息/ HTML5的的FileReader预览图像出现,缩略图像之前的上传服务器功能于jQuery的上/ –

+0

我知道,我这样做,但点击后提交页面重新加载(因为我使用控制器),我看到旧的。此外,我需要在其他子页面上查看它。 –

回答

1

有很多方法可以做你的形式在这里面 您可以使用HTML文件API。

$(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]); 
    }); 
}); 

这会很好。要么你可以让你的图像预览看起来更好。 图像预览元素使用CSS代码

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

例如

<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> 
} 

我希望这帮助

+0

完美的作品! “reader.readAsDataURL(”值得记住:) –

+0

我可以更新其他视图的图像吗?我的意思是上传一个,并在其他网页上看到新的图像?图像正确保存并在相同的视图中看起来更新,但在其他页面上则不是。 –