<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<!-- IE需要es6-promise -->
<script src="/WoniuxyLearn/page/js/jquery.min.js"></script>
</head>
<script type="text/javascript">
function doIt(){
//获取文件对象
var file = document.querySelector("#fileDemo").files[0]
//创建新文件对象(实现更名)
var newfile = new File([file], new Date().getTime()+".jpg",{type:"image/jpeg"});
//以下为预览图片代码
var reader = new FileReader();
reader.onload = function (oFREvent) {
document.querySelector("#uploadPreview").src = oFREvent.target.result;
};
reader.readAsDataURL(newfile);
console.log(reader);
}
//以下是上传图片的方法
reader.onloadend = function() {
// 这个事件在读取结束后,无论成功或者失败都会触发
if (reader.error) {
console.log(reader.error);
} else {
document.getElementById("bytesRead").textContent = file.size;
// 构造 XMLHttpRequest 对象,发送文件 Binary 数据
var xhr = new XMLHttpRequest();
xhr.open(/* method */ "POST",
/* target url */ "upload.jsp?fileName=" + file.name
/*, async, default to true */);
xhr.overrideMimeType("application/octet-stream");
xhr.sendAsBinary(reader.result);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log("upload complete");
console.log("response: " + xhr.responseText);
}
}
}
}
}
reader.readAsBinaryString(newfile);
</script>
<body>
<input type="file" id="fileDemo"><input type="button" value="预览" οnclick="doIt()"/>
<img id="uploadPreview">
</body>
</html>
js图片预览,上传,前端修改文件名
最新推荐文章于 2024-08-30 17:31:51 发布