javascript - 有没有办法上传和预览div上的图像(替换背景图像)而不刷新页面?

时间:2017-06-28 06:11:45

标签: javascript jquery css asp.net image

我有一个带有默认背景图像的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?
     }

2 个答案:

答案 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>

答案 1 :(得分: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/