您的位置:首页 > Web前端 > HTML5

js html5 上传文件、多文件,服务器 端php

2017-06-09 13:40 375 查看
表单里面的 enctype=”multipart/form-data” 不能少,

使用的 是 jq 方式,

XMLHttpRequest 对象是 js 写法,下面注释了,

两种方式,都需要 浏览器 支持 html5

<!-- html + js 代码  -->
<!DOCTYPE html>
<html>
<hrad>
<script src="http://res.526jia.com/js/jquery-1.11.0.min.js"></script>
</head>
<body>
<form enctype="multipart/form-data" action="http://www.code.com/test/test2" method="post" id="form1">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type=file name="file[]" size="20" id="file" multiple="multiple">
<input type=submit value="上传文件">
<em id="test"> hhhhhhhhh </em>
</form>
</body>
<script>
$('#test').click(function(){
//var fileobj = document.getElementById("file").files[0];
var url = 'http://www.code.com/test/test2';
var file= $('#form1')['0'].files;
var file= document.getElementById('file').files;
var form = new FormData();
for( i=0; i<file.length; i++ )
{
form.append( "file["+i+"]", file[i] );
}
// var form = new FormData();
// form.append('authour', 'okay');
// form.append('upfile', fileobj);
// XMLHttpRequest 对象
// var xhr = new XMLHttpRequest();
// xhr.open("post", url, true);
// xhr.send(form);
// xhr.onreadystatechange = function()
// {
//  if( xhr.readyState == 4 )
//  {
//      if( xhr.status == 200 )
//      {
//          console.log( JSON.parse( xhr.responseText ) );
//      }
//  }
// }
$.ajax( {
url:url,
type:'post',
data:form,
async:false,
cache:false,
contentType:false,
processData:false,
dataType:'json' ,
success:function(res){
console.log( res );
} } );
});
</script>
</html>


下面 是 服务器 端代码,,我的是 php 代码

是 将 文件 存储 到 服务器的 代码

我调用的 是 php ci 框架 封装 好的 文件上传类

由于是 支持 多文件上传, 我封装的不是 太好

public function test2()
{
if( empty( $_FILES ) ) die( 'not files' );
// 如果 是 单文件 上传,,转成 多文件 状态上传
$files = [];
if( is_array( $_FILES['file']['name'] ) )
{
$num = count($_FILES['file']['name'] );
for( $k=0; $k<$num; $k++ )
{
foreach ($_FILES['file'] as $key => $value)
{
$files['upfile'.$k][$key] = $value[$k];
}
}
$_FILES = $files;
}

$config = [
'upload_path'   =>  './upload/test',
'allowed_types' =>  'gif|jpg|jpg|jpeg|rar|zip',
'file_name'     =>  'haha.jpg'
];

if( ! is_dir( $config['upload_path'] ) )
mkdir($config['upload_path'], 777, true);

$this->load->library( 'upload', $config );

foreach ($_FILES as $key => $value) {
# code...
if( ! $this->upload->do_upload($key) )
{
//echo json_encode( ['msg'=>$this->upload->display_errors(), 'type'=> 'error' ] );
var_dump( $this->upload->display_errors() );
}else{
//echo json_encode( ['msg'=> $this->upload->data(), 'type'=>'success'] ) ;
var_dump( $this->upload->data() ) ;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息