Jquery FormData upload image file

For example

HTML

<div class="form-group">
   <label class="col-sm-3 control-label">图片</label>
   <div class="col-sm-4">
       <input type="text" class="form-control js-edit-img" placeholder="填入图片链接">
   </div>
   <div class="col-sm-4">
       <label for="js-upload-img" class="btn btn-info">上传图片</label>
       <input id="js-upload-img" accept="image/*" name="upload_image" type="file" value="" class="hide">
   </div>
</div>

JS

<script type="text/javascript">
   var UploadImage = {
       init:function() {
           this.build();
           this.initEvent();
       },
       build:function () {
           this.$editUpload    = $("#js-upload-img");
           this.$showImage     = $(".js-show-img");
           this.$editImage     = $(".js-edit-img");
       }, 
       initEvent:function () {
           var self = this;    
    
           self.uploadImage();
       },
       uploadImage:function() {
           var self = this;
           //direct input image url
           self.$editImage.blur(function(){
               self.$showImage.prop('src', $(this).val());
           });
           
           //upload image file
           self.$editUpload.on('change', function(e){
           		 console.log($(this).val()); 
                console.log(this.files[0]); //Pay attention to this!!!
               var formData = new FormData();
               formData.append('upload_image', this.files[0]);
               $.ajax({  
                   url: '/upload.php?action=upload', 
                   type:'POST',
                   cache:false,
                   data: formData,
                   processData: false,
                   contentType: false,
                   success : function(result) {
                      console.log(result);
                   },
                   error:function(){
                       alert('稍后重试');
                   }
               });

           });
       },
   };
   UploadImage.init();
</script>

Reference

https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值