上传过程:
1,使用input:type=file读取本地图片;
2,使用new FileReader(将)图片转化为base64位
3,使用ajax将图片上传服务器,后台反馈图片地址;
4,图片回显;
html
其中知识点:
1.input标签type为file的是读取本地文件
2.input中的accept属性:accept 属性只能与 配合使用。它规定能够通过文件上传进行提交的文件类型。在文件上传中使用 accept 属性,本例中的输入字段可以接受 GIF 和 JPEG 两种图像,例如:,如果不限制图像的格式,可以写为:accept=“image/*”。
<div id="imgt" style="float: left;position: relative;">
<img src="img/imgt.png" id="head">
<input type="file" accept="image/*" id="photo2" onchange="photo(2)">
</div>
js
其中知识点:
1.使用时选取本地文件之后,通过获取该input标签,然后找到它的file属性,会发现是一个数组,因为我们不一定只选择一个文件,所以选择多个文件时,file会是一个list
2.new FileReader()可以创建一个实例对象,该实例对象可以将图片转化为base64;
相关链接:https://www.cnblogs.com/xzybk/p/11593269.html
function photo(i) {
console.log(document.getElementById("photo" + i).files)
var file = document.getElementById("photo" + i).files[0]
console.log(file)
var reader = new FileReader();
// console.log(reader+'123')
reader.onload = function(a) {
console.log(a)
var result = this.result; //图片base64字符串
// var result = this.result.split(",")[1];
console.log(this.result)
$("#head").attr("src",result)
$.ajax({
type: "get",
async: false,
url: "http://192.168.1.141:8199/uploadImg",
data: {
MultipartFile: this.result.split(",")[1]
},
dataType: "json",
timeout: 50000,
success: function(res) {
console.log(res)
},
error: function(xhr, type){
alert('上传超时啦,再试试');
}
});
};
reader.readAsDataURL(file); //Base64
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)