To execute an event after clicking a button, open the local file management system, then select the file, and then select upload
世界只因有你2017-05-16 13:38:56
A method encapsulated some time ago, using ajax and formData methods to implement file upload and display the upload progress during the upload process
js
$('#upload').on('click',function(){
var xhr = new XMLHttpRequest();
xhr.open('post','../PHP/post_file.php',true);
// 获取上传进度
xhr.upload.onprogress = (ev)=>{
var scale = Math.round( (ev.loaded/ev.total)*100 );
$('.text').html( scale + '%');
$('.progress').css('width', scale + '%');
};
xhr.onload = ()=>{
console.log('上传成功');
};
// 通过file表单的files属性拿到文件数据 通过formData将数据转换为二进制格式
var fileInfo = new FormData();
fileInfo.append( 'file',$('#iptFile')[0].files[0] );
// 发送数据
xhr.send(fileInfo);
});
html
<form action="">
<input type="file" id="iptFile">
<input type="button" id="upload" value="点击上传"/>
</form>
<p class="box">
<p class="progress"></p>
<p class="text">
0%
</p>
</p>
css
.box{
position: relative;
width: 400px;
height: 50px;
border:1px solid #000;
margin-top:30px;
}
.progress{
width: 0%;
height: 100%;
background-color: red;
}
.text{
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
text-align: center;
}
php (php is not written by me)
<?php
header('Content-type:text/html; charset="utf-8"');
$upload_dir = 'uploads/';
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status(array('code'=>1,'msg'=>'错误提交方式'));
}
if(array_key_exists('file',$_FILES) && $_FILES['file']['error'] == 0 ){
$pic = $_FILES['file'];
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status(array('code'=>0,'msg'=>'上传成功','url'=>$upload_dir.$pic['name']));
}
}
echo $_FILES['file']['error'];
exit_status(array('code'=>1,'msg'=>'出现了一些错误'));
function exit_status($str){
echo json_encode($str);
exit;
}
?>
需要在服务器环境下运行,我用的是wamp,上传的文件会存到和php同级下的uploads文件夹中
漂亮男人2017-05-16 13:38:56
I just encountered a problem with uploading images on the front end two days ago. This article is my record. See if it helps. Portal
PHP中文网2017-05-16 13:38:56
You can use <input type="file" /> to achieve this, and then change the input style through css