2017-06-28 27 views
0

我有一個div(框)與默認背景圖像。我希望允許用戶通過替換背景圖片而不刷新頁面來上傳圖片和預覽。提前致謝。下面是我的代碼:JavaScript的 - 有沒有辦法上傳和預覽圖像的div(替換背景圖像),而不刷新頁面?

CSS:

#box { 
    width: 200px; 
    height: 200px; 
    box-shadow: inset 1px 1px 40px 0 rgba(0,0,0,.45); 
    border-bottom: 2px solid #fff; 
    border-right: 2px solid #fff; 
    margin: 5% auto 0 auto; 
    background-image: url('../images/Default_Img.png'); 
    background-repeat: no-repeat; 
    background-size: contain; 
    border-radius: 5px; 
    overflow: hidden; 
    } 
#overlay { 
    width: 200px; 
    height: 200px; 
    background: rgba(0,0,0,.75); 
    text-align: center; 
    padding: 45px 0 66px 0; 
    opacity: 0; 
    -webkit-transition: opacity .25s ease; 
    -moz-transition: opacity .25s ease; 
} 

#box:hover #overlay { 
    opacity: 0.5; 
} 

ASP:

<div id="box"> 
    <div id="overlay"> 
      <asp:FileUpload ID="fileUpload" runat="server" style="visibility:hidden" onchange="readURL(this);"/> 
      <asp:LinkButton ID="btnUpload" runat="server" CssClass="btn btn-default" ><i class="fa fa-upload"></i> Upload</asp:LinkButton> 
     </div> 
</div> 

的Javascript:

$(document).ready(function() { 
      $('#<%= btnUpload.ClientID %>').click(function (e) { 
       $('#<%= fileUpload.ClientID %>').click(); 
       return false; 
      }); 
     }); 

function readURL(input) { 
    if (input.files && input.files[0]) { 
     // what to do here to get image url and replace background-image? 
    } 
+0

上傳文件的AJAX。 –

+0

你只是想上傳文件?或只想預覽? –

回答

0

試試這個:

function readURL(input) { 
 
    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]); 
 
    } 
 
} 
 

 
$("#imgInp").change(function(){ 
 
    readURL(this); 
 
    // call ajax here to uplaod the image 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form id="form1" runat="server"> 
 
     <input type='file' id="imgInp" /> 
 
     <img id="blah" src="#" alt="your image" /> 
 
    </form>

0

你可以使用爲目的..

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <canvas id="myCanvas" style="width: 150px; height: 150px;"></canvas> 
    <input id="fileupload" type="file" placeholder="" accept=".png,.jpg,.jpeg,.gif" /> 

試試這個..

$(document).ready(function() { 
$("input[type=file]").change(function(e){ 
var canvas = $('#myCanvas')[0]; 
var ctx = canvas.getContext('2d'); 
var reader = new FileReader(); 
reader.onload = function (event) { 

    var img = new Image(); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    img.onload = function() { 
    canvas.width = img.width; 
    canvas.height = img.height; 
    ctx.drawImage(img, 0, 0); 
    } 
    img.src = event.target.result; 
} 
reader.readAsDataURL(e.target.files[0]); 
}); 
}); 

的jsfiddle:https://jsfiddle.net/knL5n95r/2/

相關問題