H5 手机端拍照上传测试

由 夕空 撰写于  2020年5月25日
<!DOCTYPE html>
<html lang="zh-cn">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手机端拍照测试</title>
<style>
.camera,#btn{
display: inline-block;font-size: 1rem;line-height: 2.4;padding: 0 1em;
background-color: orangered;color: white;
}
.camera input{display: none;}
#btn{display: none;float: right;}
</style>
</head>

<body>
<p>
<!-- 录像:<input type="file" accept="video/*" capture="camera"> -->
</p>
<p>
<label class="camera">拍照<input type="file" accept="image/*" capture="camera" id="file_input"></label>
<button id="btn" onclick="upfile()">确定</button>
</p>
<div id="result"></div>
<script>
var result = document.getElementById("result");
var input = document.getElementById("file_input");
var btn = document.getElementById("btn");

if (typeof FileReader === 'undefined') {
result.innerHTML = "抱歉,你的浏览器不支持预览图片!";
input.setAttribute('disabled', 'disabled');
} else {
input.addEventListener('change', readFile, false);
}


function readFile() {
var file = this.files[0];
if (!/image\/\w+/.test(file.type)) {
alert("非图像类型文件");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);

reader.onload = function (e) {
result.innerHTML = '<img width="100%" src="' + this.result + '" alt=""/>';
btn.style.display="block";
}
}

function upfile() {
var formData = new FormData();
formData.append('file', input.files[0]);
// 原生Ajax
var xhr = new XMLHttpRequest();
// xhr.responseType = "json";
xhr.overrideMimeType("application/json");
xhr.open('POST', 'http://www.***.com/api/upload/img_file', true)
xhr.onloadend = function (e) {
console.log(xhr.response, '---', xhr.responseText);
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
var data = JSON.parse(xhr.response);
console.log(data)
alert("图片上传成功")
} else {
console.log('错误' + xhr.status)
alert("图片上传失败!")
}
};
xhr.onerror = function (e) {
console.log("错误", e);
alert("图片上传错误!")
};
xhr.send(formData);
}
</script>
</body>

</html>



声明:星耀夕空|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - H5 手机端拍照上传测试


欢迎光顾我的小站!