js上傳多個文件
① jquery 多個 上傳文件教程
jquery 實現多個上傳文件教程:
首先創建解決方案,添加jquery的js和一些資源文件(如圖片和進度條顯示等):
jquery-1.3.2.min.js
jquery.uploadify.v2.1.0.js
jquery.uploadify.v2.1.0.min.js
swfobject.js
uploadify.css
1、頁面的基本代碼如下
這里用的是aspx頁面(html也是也可的)
頁面中引入的js和js函數如下:
<scriptsrc="js/jquery-1.3.2.min.js"type="text/javascript"></script>
<scriptsrc="js/jquery.uploadify.v2.1.0.js"type="text/javascript"></script>
<scriptsrc="js/jquery.uploadify.v2.1.0.min.js"type="text/javascript"></script>
<scriptsrc="js/swfobject.js"type="text/javascript"></script>
<linkhref="css/uploadify.css"rel="stylesheet"type="text/css"/>
</script>
js函數:
<scripttype="text/javascript">
$(document).ready(function(){
$("#uploadify").uploadify({
'uploader':'image/uploadify.swf',//uploadify.swf文件的相對路徑,該swf文件是一個帶有文字BROWSE的按鈕,點擊後淡出打開文件對話框
'script':'Handler1.ashx',//script:後台處理程序的相對路徑
'cancelImg':'image/cancel.png',
'buttenText':'請選擇文件',//瀏覽按鈕的文本,默認值:BROWSE。
'sizeLimit':999999999,//文件大小顯示
'floder':'Uploader',//上傳文件存放的目錄
'queueID':'fileQueue',//文件隊列的ID,該ID與存放文件隊列的div的ID一致
'queueSizeLimit':120,//上傳文件個數限制
'progressData':'speed',//上傳速度顯示
'auto':false,//是否自動上傳
'multi':true,//是否多文件上傳
//'onSelect':function(e,queueId,fileObj){
//alert("唯一標識:"+queueId+" "+
//"文件名:"+fileObj.name+" "+
//"文件大小:"+fileObj.size+" "+
//"創建時間:"+fileObj.creationDate+" "+
//"最後修改時間:"+fileObj.modificationDate+" "+
//"文件類型:"+fileObj.type);
//}
'onQueueComplete':function(queueData){
alert("文件上傳成功!");
return;
}
});
});
頁面中的控制項代碼:
<body>
<formid="form1"runat="server">
<divid="fileQueue">
</div>
<div>
<p>
<inputtype="file"name="uploadify"id="uploadify"/>
<inputid="Button1"type="button"value="上傳"onclick="javascript:$('#uploadify').uploadifyUpload()"/>
<inputid="Button2"type="button"value="取消"onclick="javascript:$('#uploadify').uploadifyClearQueue()"/>
</p>
</div>
</form>
</body>
函數主要參數:
$(document).ready(function(){
$('#fileInput1').fileUpload({
'uploader':'uploader.swf',//不多講了
'script':'/AjaxByJQuery/file.do',//處理Action
'cancelImg':'cancel.png',
'folder':'',//服務端默認保存路徑
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向後台傳遞參數,methed,arg1為參數名,uploadFile,value1為對應的參數值,服務端通過request["arg1"]
'buttonText':'UpLoadFile',//按鈕顯示文字,不支持中文,解決方案見下
//'buttonImg':'圖片路徑',//通過設置背景圖片解決中文問題,就是把背景圖做成按鈕的樣子
'multi':'true',//多文件上傳開關
'fileExt':'*.xls;*.csv',//文件過濾器
'fileDesc':'.xls',//文件過濾器詳解見文檔
'onComplete':function(event,queueID,file,serverData,data){
//serverData為伺服器端返回的字元串值
alert(serverData);
}
});
});
後台一般處理文件:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.IO;
usingSystem.Net;
usingSystem.Web;
usingSystem.Web.Services;
namespacefupload
{
///<summary>
///Handler1的摘要說明
///</summary>
publicclassHandler1:IHttpHandler
{
publicvoidProcessRequest(HttpContextcontext)
{
context.Response.ContentType="text/plain";
HttpPostedFilefile=context.Request.Files["Filedata"];//對客戶端文件的訪問
stringuploadPath=HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\";//伺服器端文件保存路徑
if(file!=null)
{
if(!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);//創建服務端文件夾
}
file.SaveAs(uploadPath+file.FileName);//保存文件
context.Response.Write("上傳成功");
}
else
{
context.Response.Write("0");
}
}
publicboolIsReusable
{
get
{
returnfalse;
}
}
}
}
以上方式基本可以實現多文件的上傳,大文件大小是在控制在10M以下/。
② 原生js實現文件上傳
function saveUser() {
var file = document.getElementById("file").files[0];
//原生ajax實現文件上傳
var formData = new FormData();
if (file) {
formData.append("file", file);
console.log(file)
}
//得到xhr對象
var xhr = null;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("post", "http://www-test.mianyazhu.com/supplier/fileSupplier/file/upload/supplier", true);//設置提交方式,url,非同步提交
// xhr.setRequestHeader("Content-Type","multipart/form-data");
xhr.onload = function () {
var data = xhr.responseText; //得到返回值
console.log(data);
}
xhr.send(formData);
}
③ bootstrap 多文件上傳
```
<link href="/static/backend/css/fileinput.css" rel="stylesheet" />
<script src="/static/backend/js/fileinput.js"></script>
<link href="/static/backend/css/fileinput.min.css" rel="stylesheet" />
<script src="/static/backend/js/fileinput.min.js"></script>
<div class="file-loading">
<input type="file" id="myfile" name="myfile[]" multiple data-allowed-file-extensions='["csv"]'/>//只能是csv 文件。 name=myfile[] 可以上傳多個文件
</div>
</div>
Js
$("#myfile").fileinput({
uploadUrl: "/backend/home/upload", //上傳地址
uploadAsync: false, //設置上傳同步非同步 此為同步
showUpload: true,
showRemove: true,
// showClose: true,
maxFileCount: 10, //表示允許同時上傳的最大文件個數
/* layoutTemplates:{
actionDelete: ''
},
browseClass: 'btn btn-primary'*/
});
後台/backend/home/upload
public function upload(){
var_mp($_FILES['myfile']);
foreach ($_FILES["myfile"]['tmp_name'] as$k =>$v){
move_uploaded_file($v,ROOT_PATH.'public'.DS.'uploads'.DS.$_FILES['myfile']['name'][$k]);
Uploads要自己創建好文件夾
}
return 1; // 上傳後要返回1
}
```
<input type="file" id="myfile" name="myfile" multiple 控制可以上傳多個 data-allowed-file-extensions='["csv"]'/>
當點擊上傳後,報錯,提示你必須選擇最少X個文件上傳。
input標簽元素屬性:data-min-file-count="2" 設置為X個文件,限制上傳文件數。
data-allowed-file-extensions= '["csv"]'
限定上傳什麼文件。
④ 如何在前端用js進行多圖片上傳
產品提了一個需求,要求在一個html中實現多行多圖片上傳,原型圖如下:
2.1 :html
html頁面由前端實現,此處增加<ul><li></li></ul>是為了配合圖片單擊放大圖片功能的實現
<ul id="ul_other">
<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>
</ul>
2.2 :js
var imgSrc_other=[];
var imgFile_other=[];
function add_file_image(id) {
var fileList =document.getElementById("file_"+id).files;// js 獲取文件對象
if (verificationFile(fileList[0])){
for(var i =0;i
var imgSrcI =getObjectURL(fileList[i]);
if (id=="other"){
imgSrc_other.push(imgSrcI);
if(fileList[i].size/1024 >100) { //大於100kb,進行壓縮上傳
fileResizetoFile(fileList[i],0.6,function(res){
imgFile_other.push(res);
})
}else{
imgFile_other.push(res);
}
}
addNewContent(id);
}
}
//新增圖片
function addNewContent(obj) {
//刪除原先
$("#ul_"+obj).html("");
//判斷循環新增
var text="";
if (obj=="other"){
for(var a =0;a < imgSrc_examReportCard.length;a++) {
text +='<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>';
}
}else{
console.log('臟數據');
}
var oldBox ="<li><div class=\"filediv\"><span>+</span>\n" +
"<input type=\"file\" id=\"file_"+obj+"\" class=\"file_input\" onchange=\"add_file_image('"+obj+"')\">\n" +
"</div></li>";
$("#ul_"+obj).html( text+localText);
}
使用formData上傳
var form =document.getElementById("form_addArchive");//表單id
var formData =new FormData(form);
$.each(imgFile_other,function(i, file){
formData.append('imgFileOther', file);
});
$.ajax({
url:url,
type:'POST',
async:true,
cache:false,
contentType:false,
processData:false,
dataType:'json',
data:formData,
xhrFields:{
withCredentials:true
},
success:function(data) {
}
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
})
後台使用@RequestParam(value ="imgFileOther", required=false) List<MultipartFile> imgFileOther, 接受
//獲取圖片url以便顯示
//文件格式驗證
//圖片壓縮
⑤ 如何通過js完成多個文件的上傳
HTML5 file組件的新屬性
accept : 如果在file組件中增加這個屬性就可以直接控制上傳的文件類型了,實在是很方便。
multiple:是否允許選擇多個文件
HTML5 頁面代碼修改後
<img width="400" height="250"/><br />
<input type="file" id="pic" name="pic" onchange="printFileInfo()" accept="image/*" multiple="multiple"/>
<input type="button" value="上傳圖片" onclick="uploadFile()" /><br />
<div id="parent">
<div id="son"></div>
</div>
accept 的值可以參閱:IANA MIME 類型(標准 MIME 類型的完整列表),如果使用的是DW開發的話,軟體本身就有提示。
如果選擇了多個文件,可以用JS做循環列印,看看文件的名稱,類型和大小,看演示代碼
function printFileInfo(){
var picFile = document.getElementById("pic");
var files = picFile.files;
for(var i=0; i<files.length; i++){
var file = files[i];
var div = document.createElement("div")
div.innerHTML = "第("+ (i+1) +") 個文件的名字:"+ file.name +
" , 文件類型:"+ file.type +" , 文件大小:"+ file.size
document.body.appendChild( div)
}
}
既然可以循環多文件的話,就可以嘗試多文件上傳了。
1、首先創建 XMLHttpRequest 對象
//這是全局變數。因為是示例,所以就沒有判斷瀏覽器類型,低版本IE這么寫的話會出問題的
var xhr = new XMLHttpRequest()
2、上篇介紹了進度事件(Progress) , 這次實現 progress 和 error 2個事件
error:在請求發生錯誤時觸發。
對應上傳時發生錯誤導致的上傳失敗:uploadFailed()
//上傳失敗
function uploadFailed(evt) {
alert("上傳失敗");
}
progress:在接收相應期間持續不斷觸發。
對應上傳進度方法:onprogress()
/**
* 偵查附件上傳情況 ,這個方法大概0.05-0.1秒執行一次
*/
function onprogress(evt){
var loaded = evt.loaded; //已經上傳大小情況
var tot = evt.total; //附件總大小
var per = Math.floor(100*loaded/tot); //已經上傳的百分比
$("#son").html( per +"%" );
$("#son").css("width" , per +"%");
}
最後就是上傳方法了,注意上面的html代碼中上傳用的方法也需要改成這個uploadFile()方法才能正常使用。
//上傳文件
function uploadFile() {
//將上傳的多個文件放入formData中
var picFileList = $("#pic").get(0).files;
var formData = new FormData();
for(var i=0; i< picFileList.length; i++){
formData.append("file" , picFileList[i] );
}
//監聽事件
xhr.upload.addEventListener("progress", onprogress, false);
xhr.addEventListener("error", uploadFailed, false);//發送文件和表單自定義參數
xhr.open("POST", "upload");
//記得加入上傳數據formData
xhr.send(formData);
}
⑥ 請高手給一個JS多文件上傳的例子(必須兼容IE)解決追加50分。請看補充。
一、Servlet實現文件上傳,需要添加第三方提供的jar包
下載地址:
1) commons-fileupload-1.2.2-bin.zip: 點擊打開鏈接
2) commons-io-2.3-bin.zip: 點擊打開鏈接
接著把這兩個jar包放到 lib文件夾下:
二:文件上傳的表單提交方式必須是POST方式,
編碼類型:enctype="multipart/form-data",默認是 application/x-www-form-urlencoded
比如:
<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、舉例:
1.fileupload.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'fileuploadjsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
<!-- enctype 默認是 application/x-www-form-urlencoded -->
<form action="FileUpLoad" enctype="multipart/form-data" method="post" >
用戶名:<input type="text" name="usename"> <br/>
上傳文件:<input type="file" name="file1"><br/>
上傳文件: <input type="file" name="file2"><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.實際處理文件上傳的 FileUpLoad.java
package comservletfileupload;
import javaioFile;
import javaio*;
import javaioIOException;
import javaioPrintWriter;
import javautilList;
import javaxservletServletException;
import javaxservlethttpHttpServlet;
import ;
import ;
import ;
import ;
import ;
import ;
/**
*
* @author Administrator
* 文件上傳
* 具體步驟:
* 1)獲得磁碟文件條目工廠 DiskFileItemFactory 要導包
* 2) 利用 request 獲取 真實路徑 ,供臨時文件存儲,和 最終文件存儲 ,這兩個存儲位置可不同,也可相同
* 3)對 DiskFileItemFactory 對象設置一些 屬性
* 4)高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory);
* 目的是調用 parseRequest(request)方法 獲得 FileItem 集合list ,
*
* 5)在 FileItem 對象中 獲取信息, 遍歷, 判斷 表單提交過來的信息 是否是 普通文本信息 另做處理
* 6)
* 第一種 用第三方 提供的 itemwrite( new File(path,filename) ); 直接寫到磁碟上
* 第二種 手動處理
*
*/
public class FileUpLoad extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
requestsetCharacterEncoding("utf-8"); //設置編碼
//獲得磁碟文件條目工廠
DiskFileItemFactory factory = new DiskFileItemFactory();
//獲取文件需要上傳到的路徑
String path = requestgetRealPath("/upload");
//如果沒以下兩行設置的話,上傳大的 文件 會佔用 很多內存,
//設置暫時存放的 存儲室 , 這個存儲室,可以和 最終存儲文件 的目錄不同
/**
* 原理 它是先存到 暫時存儲室,然後在真正寫到 對應目錄的硬碟上,
* 按理來說 當上傳一個文件時,其實是上傳了兩份,第一個是以 tem 格式的
* 然後再將其真正寫到 對應目錄的硬碟上
*/
factorysetRepository(new File(path));
//設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室
factorysetSizeThreshold(1024*1024) ;
//高水平的API文件上傳處理
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//可以上傳多個文件
List<FileItem> list = (List<FileItem>)uploadparseRequest(request);
for(FileItem item : list)
{
//獲取表單的屬性名字
String name = itemgetFieldName();
//如果獲取的 表單信息是普通的 文本 信息
if(itemisFormField())
{
//獲取用戶具體輸入的字元串 ,名字起得挺好,因為表單提交過來的是 字元串類型的
String value = itemgetString() ;
requestsetAttribute(name, value);
}
//對傳入的非 簡單的字元串進行處理 ,比如說二進制的 圖片,電影這些
else
{
/**
* 以下三步,主要獲取 上傳文件的名字
*/
//獲取路徑名
String value = itemgetName() ;
//索引到最後一個反斜杠
int start = valuelastIndexOf("\\");
//截取 上傳文件的 字元串名字,加1是 去掉反斜杠,
String filename = valuesubstring(start+1);
requestsetAttribute(name, filename);
//真正寫到磁碟上
//它拋出的異常 用exception 捕捉
//itemwrite( new File(path,filename) );//第三方提供的
//手動寫的
OutputStream out = new FileOutputStream(new File(path,filename));
InputStream in = itemgetInputStream() ;
int length = 0 ;
byte [] buf = new byte[1024] ;
Systemoutprintln("獲取上傳文件的總共的容量:"+itemgetSize());
// inread(buf) 每次讀到的數據存放在 buf 數組中
while( (length = inread(buf) ) != -1)
{
//在 buf 數組中 取出數據 寫到 (輸出流)磁碟上
outwrite(buf, 0, length);
}
inclose();
outclose();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
eprintStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
//eprintStackTrace();
}
requestgetRequestDispatcher("filedemojsp")forward(request, response);
}
}
System.out.println("獲取上傳文件的總共的容量:"+item.getSize());
3.filedemo.jsp
<%@ page language="java" import="javautil*" pageEncoding="UTF-8"%>
<%
String path = requestgetContextPath();
String basePath = requestgetScheme()+"://"+requestgetServerName()+":"+requestgetServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'filedemojsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="stylescss">
-->
</head>
<body>
用戶名:${requestScopeusename } <br/>
文件:${requestScopefile1 }<br/>
${requestScopefile2 }<br/>
<!-- 把上傳的圖片顯示出來 -->
<img alt="go" src="upload/<%=(String)requestgetAttribute("file1")%> " />
</body>
</html>
4結果頁面:
以上就是本文的全部