HTML结构如下,并未写css,样式主要根据项目情况进行设置
<body>
<div class="wrap">
<img alt="">
</div>
<input style='display: none' id='upload-file' type="file" onchange='fileChange(this)'>
<button onclick='uploadImg()'>上传图片</button>
<button onclick='saveImg()'>保存图片</button>
</body>
js代码如下
//点击自定义按钮调用input[name+"file"]的click事件
function uploadImg() {
$('#upload-file').click()
};
//预览图片
function fileChange(file) {
if(file.files[0]) {
console.log(1);
var reader = new FileReader();
reader.readAsDataURL(file.files[0]);
reader.onload = function (event) {
$('.wrap img').attr('src', event.target.result)
}
}
}
//保存图片
function saveImg() {
var formdata = new FormData();
var images = $('#upload-file').get(0).files[0];
if(images == undefined) {
return false
} else {
formdata.append('image', images);
$.ajax({
url: 'url',
type: 'post',
data: formdata,
dataType: 'json',
processData: false,
contentType: false,
success: function (res) {
console.log(res);
}
})
}
}