悠悠楠杉
网站页面
本文实例讲述了jQuery实现文件编码成base64并通过AJAX上传的方法。分享给大家供大家参考,具体如下:
使用AJAX是无法直接上传文件的,一般都是新建个iframe在它里面完成表单提交的过程以达到异步上传文件的效果。
如此做可以达到比较好的浏览器兼容性,不过代码量会比较大,即使是使用了文件上传插件,例如plupload。
如何能达到灵活的程度呢,能像普通的AJAX提交表单数据那样将文件看成是普通表单参数来对待就好了。
灵光一闪,利用javascript的FileReader对象将文件编码成base64再传服务器不就行了么~
开始动手,丰衣足食。
<?php
// 后端对文件数据解码并保存
if (!empty($_POST)) {
$dir = base64_upload($_POST['fileBase64'], 'jpg', 'img');
exit(json_encode(['img' => $dir]));
}
function base64_upload($content, $suffix, $dir = 'topic', $filename = '')
{
$content = preg_replace('/data:.*;base64,/i', '', $content);
$content = base64_decode($content);
if(!$content){
return;
}
$path = '/upload/' . $dir . '/' . date('Ymd') . '/';
$root = $_SERVER['DOCUMENT_ROOT'];
if ($filename) {
$name = $filename . '.' . $suffix;
} else {
$name = md5(time() . mt_rand(0, 999)) . '.' . $suffix;
}
if (!is_dir($root . $path)) {
mkdir($root . $path, 0777, true);
}
$route = $path . $name;
try {
file_put_contents($root . $path . $name, $content);
} catch (\Throwable $th) {
//throw $th;
$route = '';
}
return $route;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form onsubmit="return false;">
<input type="file" id="fileup">
<img src="" class="img" style="width: 200px;">
<input type="submit" value="submit" class="submit">
</form>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
// 前端对文件进行base64编码并通过ajax向服务器传输
var fileBase64 = '';
$("#fileup").change(function() {
var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function(e) {
console.log(e.target.result);
fileBase64 = e.target.result;
$('.img').attr('src', e.target.result);
};
});
$('.submit').on('click', function() {
$.post('', {
fileBase64: fileBase64
}, function(res) {
console.log(res);
}, 'json')
})
</script>
</body>
</html>
javascript里的FileReader对象主流浏览器都支持,IE10以上支持,我觉得在为小范围提供服务时可以考虑这个异步上传文件的方式,省时又省力,兼容IE系列另当别论。
Reference:
FileReader - Web API Interfaces | MDN