Jquery FormData upload image file

苗信鸥
2023-12-01

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

 类似资料:

相关阅读

相关文章

相关问答