Asynchronous file upload is usually implemented through ajax, some friends also said that using iframe to achieve this can achieve the goal, but it is not really a asynchronous upload. If the browser does not support irame, iframe imitation upload will be ineffective, next we will look at a real example of asynchronous file upload. Asynchronous file upload is usually implemented through ajax, some friends also said that using iframe to achieve this can achieve the goal, but it is not really a asynchronous upload. If the browser does not support irame, iframe imitation upload will be ineffective, next we will look at a real example of asynchronous file upload.
Script ec (2); script
PHP code:
$ FileName = $ _ FILES ['affile'] ['name'];
$ FileType = $ _ FILES ['affile'] ['type'];
$ FileContent = file_get_contents ($ _ FILES ['affile'] ['tmp _ name']);
$ DataUrl = 'data: '. $ fileType.'; base64, '. base64_encode ($ fileContent );
$ Json = json_encode (array (
'Name' => $ fileName,
'Type' => $ fileType,
'Dataurl' => $ dataUrl,
'Username' => $ _ REQUEST ['username'],
'Accountnum' => $ _ REQUEST ['accountnum']
));
Echo $ json;
Html and JS Code
Xhr. send (FormData) Example
Script
Document. querySelector ('# afile'). addEventListener ('change', function (e ){
Var file = this. files [0];
Var fd = new FormData ();
Fd. append ("afile", file );
// These extra params aren't necessary but show that you can include other data.
Fd. append ("username", "Groucho ");
Fd. append ("accountnum", 123456 );
Var xhr = new XMLHttpRequest ();
Xhr. open ('post', 'handle _ file_upload.php ', true );
Xhr. upload. onprogress = function (e ){
If (e. lengthComputable ){
Var percentComplete = (e. loaded/e. total) * 100;
Console. log (percentComplete + '% uploaded ');
}
};
Xhr. onload = function (){
If (this. status = 200 ){
Var resp = JSON. parse (this. response );
Console. log ('server got: ', resp );
Var image = document. createElement ('img ');
Image. src = resp. dataUrl;
Document. body. appendChild (image );
};
};
Xhr. send (fd );
}, False );
Script