浏览器识别本地上传图片(转)

本文介绍了一种使用JavaScript实现的文件上传与图片预览的方法,包括通过点击按钮触发文件选择框,利用File API读取选中文件并进行格式验证,最终在页面上实时显示所选图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html:

<span class="shop_pic shop_pro" onClick="opload_file(this);" type="addButton">
添加图片<strong></strong>
</span>
<input class="change_img" type="file" name="image[]" style="display:none">

 

js:

function opload_file(obj){
  $(obj).next('input[type="file"]').click();
  $("#image_error").html('');
}

function getObjectURL(file) {
  var url = null ;
  if (window.createObjectURL!=undefined) { // basic
    url = window.createObjectURL(file) ;
  } else if (window.URL!=undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file) ;
  } else if (window.webkitURL!=undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file) ;
  }
  return url ;
}

 

$('#pic_list input[type="file"]').live('change',function(){
  var objUrl = getObjectURL(this.files[0]);
  var type = this.files[0]['type'].split("/");
  if(type[1] != "jpeg" && type[1] != "png" && type[1] != "gif"){
    $("#image_error").html("图片格式不正确");
  }else{
    var size = this.files[0]['size'];
    /* if(size > 10485760){
      //限制10M的图片
      $("#image_error").html("图片必须小于10M");
    }*/
    if (objUrl) {
      $("#image_dom").children("span[type='addButton']").html('');
      var image = '<img src="'+objUrl+'" width="191" height="126" />';
      $("#image_dom").children("span[type='addButton']").append(image);
      var strong_html = "<strong class='bg2' onclick='delImage(this);'></strong>";
      $("#image_dom").children("span[type='addButton']").append(strong_html);
      $("#image_dom").children("span[type='addButton']").attr('type','addPic');

      var num = $("#image_dom").children("span:[type='addPic']").length;
      if(num < 4){
        if(size > 10485760){
          //限制10M的图片
          $("#image_error").html("图片必须小于10M");
        }else{
          var addButton = '<span class="shop_pic shop_pro" onclick="opload_file(this);" type="addButton">';
          addButton += '添加产品<strong></strong>';
          addButton += '</span>';
          addButton += '<input class="change_img" type="file" name="image[]" style="display:none">';

          $(this).parent("#image_dom").append(addButton);
        }
      }
    }
  }
});

 

<input type="file" name="pictures[]" multiple="multiple" />

残念的是IE不支持…

转载于:https://www.cnblogs.com/xingmeng/p/4028873.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值