用jquery做一个网页版的上传文件功能可以兼容手机等移动端
下面是一个使用jQuery和HTML5的示例代码,实现了一个网页版的上传文件功能,并且可以在移动端兼容使用:
HTML代码:
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" multiple>
<button id="uploadButton">上传</button>
<div id="progressBar" style="display:none">
<div id="progress"></div>
</div>
<div id="status"></div>
<script>
$(document).ready(function() {
$('#uploadButton').click(function() {
var files = $('#fileInput').get(0).files;
if (files.length > 0) {
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('files[]', files[i]);
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
var percent = Math.round((e.loaded / e.total) * 100);
$('#progress').css('width', percent + '%');
}
});
return xhr;
},
beforeSend: function() {
$('#progressBar').show();
$('#status').empty().text('上传中...');
},
success: function(response) {
$('#status').empty().text(response);
},
complete: function() {
$('#progressBar').hide();
}
});
}
});
});
</script>
</body>
</html>
注意,上述代码中的upload.php
是上传文件的后端处理脚本,你需要根据自己的实际情况进行修改。
在upload.php
中,你可以使用$_FILES
超全局变量来访问上传的文件,进行后续的处理操作。示例代码如下:
<?php
if(isset($_FILES['files'])){
$errors= array();
$file_name = $_FILES['files']['name'];
$file_size =$_FILES['files']['size'];
$file_tmp =$_FILES['files']['tmp_name'];
$file_type=$_FILES['files']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['files']['name'])));
$extensions= array("jpeg","jpg","png");
if(in_array($file_ext,$extensions)=== false){
$errors[]="扩展名不允许,请选择 JPEG 或 PNG 文件。";
}
if($file_size > 2097152){
$errors[]='文件大小超过 2MB 的限制。';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"uploads/".$file_name);
echo "文件上传成功。";
}else{
print_r($errors);
}
}
?>
以上代码实现了一个基本的文件上传功能,通过选择文件后点击上传按钮,将文件传递给后端脚本进行处理,并在页面上显示上传进度和上传状态。
希望对你有帮助

原文地址: http://www.cveoy.top/t/topic/imts 著作权归作者所有。请勿转载和采集!