2016-11-02 30 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

我可以更新其他視圖的圖像嗎?我的意思是上傳一個,並在其他網頁上看到新的圖像?圖像正確保存並在相同的視圖中看起來更新,但在其他頁面上則不是。 –