<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>
<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>
https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects