欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

js多文件上传

发布时间:2025/6/17 编程问答 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 js多文件上传 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一、HTML

选择文件的时候可以选择多个文件,这个需要我们在input file 里面加入一个属性multiple="multiple" 这样就可以框选文件了

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>多文件上传</title> </head><body> <div style="text-align:center;margin:100px"><input type="file" id="file" name="file" multiple="multiple"><button onclick="xhr2()">多文件上传</button> </div> </body> </html>

二、JS

下面使用到的知识参考自:

http://www.cnblogs.com/snowinmay/archive/2013/07/17/3195072.html

http://www.jb51.net/article/89998.htm

https://my.oschina.net/u/1866405/blog/335987

//多文件上传函数 function xhr2(){var xhr = new XMLHttpRequest();//第一步//定义表单变量var file = document.getElementById('file').files;//console.log(file.length);//新建一个FormData对象var formData = new FormData(); //++++++++++//追加文件数据for(i=0;i<file.length;i++){ formData.append("file["+i+"]", file[i]); //++++++++++ } //formData.append("file", file[0]); //++++++++++//post方式xhr.open('POST', '2.php'); //第二步骤//发送请求xhr.send(formData); //第三步骤//ajax返回xhr.onreadystatechange = function(){ //第四步if ( xhr.readyState == 4 && xhr.status == 200 ) {console.log( xhr.responseText );//打印数据到控制台 }};//设置超时时间xhr.timeout = 100000;xhr.ontimeout = function(event){alert('请求超时!');} }

三、PHP

这里就是简单的接收文件和移动文件

if($_POST){print_r($_FILES["file"]); for($i=0;$i<count($_FILES["file"]['name']);$i++){$name=$_FILES["file"]["name"][$i];move_uploaded_file($_FILES["file"]["tmp_name"][$i],iconv("UTF-8","gb2312",$name));} }

 

转载于:https://www.cnblogs.com/phpyangbo/p/6148327.html

总结

以上是生活随笔为你收集整理的js多文件上传的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。