用户从浏览器中选择文件后如何立即上传图像?
就像在 Facebook 中一样,当您需要上传封面或个人资料图片时,您需要 选择文件,然后开始上传。
我现在只有我的输入标签
<input id="chaf" type="file"/>
以及可以在选择文件后运行该函数的js
$('#chaf').change(function(){
// Upload image start
});
但是我怎样才能以这种方式将数据发送到php呢?
最佳答案
您可以使用 Ajax 将文件上传为 Base64 字符串(无需刷新)。 像这样的事情。
$(document).on("change", ".custom-file-input", this, function(e){
GetBase64( e.target );
});
function GetBase64( input ) {
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
var str = e.target.result;
/* preview it ( if you wanted to ) */
$('#preview-img').attr( "src", str );
/* upload it to server */
UploadFile( str );
};
FR.readAsDataURL( input.files[0] );
}
}
function UploadFile( file_str ) {
console.log( file_str );
/* use $.ajax to upload your file */
}
引用这个答案在磁盘中存储base64 base64 string to an image file
在 php 中是这样的
<?php
$base64Str = $_REQUEST[ "your-post-variable" ];
$img = explode(',', $base64Str);
$fp = fopen( "my-image.png" , "wb");
fwrite($fp, base64_decode( $img[1]) );
fclose($fp);
?>
关于javascript - 选择文件后立即上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669838/