<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form action="" method="">
<label>
<input type="file" onchange="upfile(this, '#form01234');PreviewImage(this, 'file0123');" />
<div id="file0123"></div>
<input type="hidden" name="ico" id="form01234" />
</label>
</form>
<script>
const url = "index.php"; //处理图片的接口
//选中图片预览
function PreviewImage(imgFile, id) {
if (imgFile.value != undefined) {
var ext = imgFile.value.substring(imgFile.value.lastIndexOf(".")).toLowerCase();
if (!ext.match(/(?:jpg|jpeg|gif|png|bmp)$/)) {
imgFile.focus();
return;
}
document.getElementById(id).innerHTML =
'<img width="100%" src="' + window.URL.createObjectURL(imgFile.files[0]) + '" />';
}
}
function upfile(file, form) {
var formData = new FormData();
formData.append("file", $(file)[0].files[0]);
$.ajax({
url,
type: "POST",
data: formData,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false,
AccessControlAllowOrigin: "*", // 告诉jQuery不要去设置Content-Type请求头
beforeSend: function() {
console.log("正在进行,请稍候");
},
success: function(data) {
var json = JSON.parse(data);
$(form).val(json["url"]);
},
error: function(data) {
console.log("上传失败");
}
});
}
</script>
</body>
</html>