一个前端上传文件按钮功
<input type="file" id="file" >
$("#file").bind("change",function () {
var fileinfo = document.getElementById("file").files[0];
var reader = new FileReader();
reader.readAsDataURL(fileinfo);
reader.onload = function(){
//console.log(reader.result);
};
})
选择了readerAsDataURL 方法 读取数据,因为试过其他方式,发现其他方式获取数据后在传到后端时,容易引起浏览器崩溃
由于readerAsDataURL方法,获取的返回值,并不是完全的数据,而是加了一些前缀
data = reader.result.split(",")[1]
这样才是完整的数据
使用ajax发送数据
jQuery.ajax({
dataType:"json",
data:JSON.stringify({"fileinfo":data,"name":filename,"path":path,}),
url:"/task/getfile/",
type:"post",
cache:false,
processData:false,
contentType:false,
success:function (data) {
if(data.status==0){
document.getElementById("text_info").innerText = "文件成功上传!"
}else{
document.getElementById("text_info").innerText = "文件上传失败!"
}
},
});
后端接受数据就OK。
由于readAsDataURL将文件转为了base64格式,后端只需要转回去
打开文件(文件名后缀要一致!一致!一致!)