王新阳

wangxinyang

FileReader文件转base64并上传简单示例

FileReader手册 https://developer.mozilla.org/en-US/docs/Web/API/FileReader

html_html5增强的文件上传域_使用FileReader读取文件内容https://www.cnblogs.com/isXianYue/p/13196444.html

HTML

<input type="file" id="file">
<script>
$('#file').change(function(){
	var This=$(this);
	var reader=new FileReader();
	reader.onload=function(){
		$.post('/base64.php',{
				base64:reader.result,
				name:This.get(0).files[0]['name']
			}, function(res){
				alert(res);
		},'text');
	};
	//console.log(This.get(0).files[0]);
	reader.readAsDataURL(This.get(0).files[0]);
});
</script>

PHP

<?php
$base64 = $_POST['base64'];
$name = $_POST['name'];
$file = substr($base64,strpos($base64,','));
$mime = substr(substr($base64, 0, strpos($base64,';')), 5);

file_put_contents($name, base64_decode($file));
echo 'ok';
2021-09-21
2024-11-22 星期五 农历十月二十二