Ajax上传文件进度条Codular(2)

var _submit = document.getElementById('_submit'), _file = document.getElementById('_file'), _progress = document.getElementById('_progress'); var upload = function(){ if(_file.files.length === 0){ return; } var data = new FormData(); data.append('SelectedFile', _file.files[0]); var request = new XMLHttpRequest(); request.onreadystatechange = function(){ if(request.readyState == 4){ try { var resp = JSON.parse(request.response); } catch (e){ var resp = { status: 'error', data: 'Unknown error occurred: [' + request.responseText + ']' }; } console.log(resp.status + ': ' + resp.data); } }; request.upload.addEventListener('progress', function(e){ _progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%'; }, false); request.open('POST', 'upload.php'); request.send(data); } _submit.addEventListener('click', upload);

现在到了PHP...

PHP

这是我们使用的代码,你将注意到一些区别,主要是我们用最上面的JSON方法来返回值都作为JSON格式输出.这个PHP与之前文章中的代码相同,这也就意味着该方法只适用于小于500Kb的PNG图片.此外,成功信息将返回已上传文件的路径:

<?php // Output JSON function outputJSON($msg, $status = 'error'){ header('Content-Type: application/json'); die(json_encode(array( 'data' => $msg, 'status' => $status ))); } // Check for errors if($_FILES['SelectedFile']['error'] > 0){ outputJSON('An error ocurred when uploading.'); } if(!getimagesize($_FILES['SelectedFile']['tmp_name'])){ outputJSON('Please ensure you are uploading an image.'); } // Check filetype if($_FILES['SelectedFile']['type'] != 'image/png'){ outputJSON('Unsupported filetype uploaded.'); } // Check filesize if($_FILES['SelectedFile']['size'] > 500000){ outputJSON('File uploaded exceeds maximum upload size.'); } // Check if the file exists if(file_exists('upload/' . $_FILES['SelectedFile']['name'])){ outputJSON('File with that name already exists.'); } // Upload file if(!move_uploaded_file($_FILES['SelectedFile']['tmp_name'], 'upload/' . $_FILES['SelectedFile']['name'])){ outputJSON('Error uploading file - check destination is writeable.'); } // Success! outputJSON('File uploaded successfully to "' . 'upload/' . $_FILES['SelectedFile']['name'] . '".', 'success');

如果将所有内容都放在一起,您应该可以将文件上传到您期望的位置,并在浏览器的控制台内成功返回。

结束语

还有一些比较容易而又有效的方式来增强用户体验.通过将文件队列的多个文件加入到FormData,可以实现多文件上传. 有一点要说明,如果你是在本地做测试,你可能没办法看到进度条逐步变化,这取决于你本地机器的上传速度,我建议在服务器上使用较大的png文件做测试.

以上所述是小编给大家介绍的Ajax上传文件进度条Codular,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjsxzy.html