Uploadify是一個Jquery框架下處理批量文件上傳的插件,支持多種服務器端軟件。
文檔:http://www.uploadify.com/documentation/
今天根據文檔寫了個批量上傳的的功能..
下面直接進入主題:
界面效果:
界面代碼:
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
- <%
- String path = request.getContextPath();
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Uploadify上傳</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <link rel="stylesheet" href="uploadify/uploadify.css" type="text/css"></link>
- <script type="text/javascript" src="uploadify/jquery-1.7.2.min.js"></script>
- <script type="text/javascript"
- src="uploadify/jquery.uploadify-3.1.min.js"></script>
- <script type="text/javascript">
- $(function() {
- $("#file_upload").uploadify({
- 'height' : 27,
- 'width' : 80,
- 'buttonText' : '瀏 覽',
- 'swf' : '<%=path%>/uploadify/uploadify.swf',
- 'uploader' : '<%=path%>/servlet/UploadifySerlet',
- 'auto' : false,
- 'fileTypeExts' : '*.xls',
- 'formData' : {'userName':'','qq':''},
- 'onUploadStart' : function(file) {
- //校驗
- var name=$('#userName').val();
- if(name.replace(/\s/g,'') == ''){
- alert("名稱不能爲空!");
- return false;
- }
- //校驗
- var qq=$('#qq').val();
- if(qq.replace(/\s/g,'') == ''){
- alert("QQ不能爲空!");
- return false;
- }
- $("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq});
- //$("#file_upload").uploadify("settings", "qq", );
- }
- });
- });
- </script>
- </head>
- <body>
- 名稱: <input type="text" id="userName" name="userName" value="妞見妞愛">
- <br>
- QQ: <input type="text" id="qq" name="qq" value="609865047">
- <br>
- <input type="file" name="uploadify" id="file_upload" />
- <hr>
- <a href="javascript:$('#file_upload').uploadify('upload','*')">開始上傳</a>
- <a href="javascript:$('#file_upload').uploadify('cancel', '*')">取消所有上傳</a>
- </body>
- </html>
關於各個參數的介紹,網上也有很多。。我們也可以在 jquery.uploadify-3.1.js 中找到。
- var settings = $.extend({
- // Required Settings
- id : $this.attr('id'), // The ID of the DOM object
- swf : 'uploadify.swf', // The path to the uploadify SWF file
- uploader : 'uploadify.php', // The path to the server-side upload script
- // Options
- auto : true, // Automatically upload files when added to the queue
- buttonClass : '', // A class name to add to the browse button DOM object
- buttonCursor : 'hand', // The cursor to use with the browse button
- buttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the button
- buttonText : 'SELECT FILES', // The text to use for the browse button
- checkExisting : false, // The path to a server-side script that checks for existing files on the server
- debug : false, // Turn on swfUpload debugging mode
- fileObjName : 'Filedata', // The name of the file object to use in your server-side script
- fileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)
- fileTypeDesc : 'All Files', // The description for file types in the browse dialog
- fileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)
- height : 30, // The height of the browse button
- method : 'post', // The method to use when sending files to the server-side upload script
- multi : true, // Allow multiple file selection in the browse dialog
- formData : {}, // An object with additional data to send to the server-side upload script with every file upload
- preventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)
- progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file upload
- queueID : false, // The ID of the DOM object to use as a file queue (without the #)
- queueSizeLimit : 999, // The maximum number of files that can be in the queue at one time
- removeCompleted : true, // Remove queue items from the queue when they are done uploading
- removeTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to true
- requeueErrors : false, // Keep errored files in the queue and keep trying to upload them
- successTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploading
- uploadLimit : 0, // The maximum number of files you can upload
- width : 120, // The width of the browse button
上面是默認的設置。。。
服務器端代碼:
- package com.yangpan.uploadify;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.text.SimpleDateFormat;
- import java.util.Arrays;
- import java.util.Date;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Random;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.fileupload.FileItem;
- import org.apache.commons.fileupload.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- public class UploadifySerlet extends HttpServlet {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- //上傳文件的保存路徑
- protected String configPath = "attached/";
- protected String dirTemp = "attached/temp/";
- protected String dirName = "file";
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- response.setContentType("text/html; charset=UTF-8");
- PrintWriter out = response.getWriter();
- //文件保存目錄路徑
- String savePath = this.getServletContext().getRealPath("/") + configPath;
- // 臨時文件目錄
- String tempPath = this.getServletContext().getRealPath("/") + dirTemp;
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
- String ymd = sdf.format(new Date());
- savePath += "/" + ymd + "/";
- //創建文件夾
- File dirFile = new File(savePath);
- if (!dirFile.exists()) {
- dirFile.mkdirs();
- }
- tempPath += "/" + ymd + "/";
- //創建臨時文件夾
- File dirTempFile = new File(tempPath);
- if (!dirTempFile.exists()) {
- dirTempFile.mkdirs();
- }
- DiskFileItemFactory factory = new DiskFileItemFactory();
- factory.setSizeThreshold(20 * 1024 * 1024); //設定使用內存超過5M時,將產生臨時文件並存儲於臨時目錄中。
- factory.setRepository(new File(tempPath)); //設定存儲臨時文件的目錄。
- ServletFileUpload upload = new ServletFileUpload(factory);
- upload.setHeaderEncoding("UTF-8");
- try {
- List items = upload.parseRequest(request);
- Iterator itr = items.iterator();
- String name = "";
- String qq = "";
- while (itr.hasNext()) {
- FileItem item = (FileItem) itr.next();
- String fileName = item.getName();
- long fileSize = item.getSize();
- if (!item.isFormField()) {
- String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
- String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
- try{
- File uploadedFile = new File(savePath, newFileName);
- /*
- * 第一種方法
- *
- * 好處: 一目瞭然..簡單啊...
- * 弊端: 這種方法會導致上傳的文件大小比原來的文件要大
- *
- * 推薦使用第二種
- */
- //item.write(uploadedFile);
- //--------------------------------------------------------------------
- //第二種方法
- OutputStream os = new FileOutputStream(uploadedFile);
- InputStream is = item.getInputStream();
- byte buf[] = new byte[1024];//可以修改 1024 以提高讀取速度
- int length = 0;
- while( (length = is.read(buf)) > 0 ){
- os.write(buf, 0, length);
- }
- //關閉流
- os.flush();
- os.close();
- is.close();
- System.out.println("上傳成功!路徑:"+savePath+"/"+newFileName);
- out.print("1");
- }catch(Exception e){
- e.printStackTrace();
- }
- }else {
- String filedName = item.getFieldName();
- if (filedName.equals("userName")) {
- name = item.getString();
- }else {
- qq = item.getString();
- }
- System.out.println("FieldName:"+filedName);
- System.out.println("String:"+item.getString("UTF-8"));//避免中文亂碼
- //System.out.println("String():"+item.getString(item.getName()));
- System.out.println("===============");
- }
- }
- } catch (FileUploadException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- out.flush();
- out.close();
- }
- }
WEB.XML
- <servlet>
- <servlet-name>UploadifySerlet</servlet-name>
- <servlet-class>
- com.yangpan.uploadify.UploadifySerlet
- </servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>UploadifySerlet</servlet-name>
- <url-pattern>/servlet/UploadifySerlet</url-pattern>
- </servlet-mapping>
基本設置
swf:主要Flash文件路徑,默認uploadify.swf,如果同調用文件在同一不目錄下可以忽略
uploader:後臺處理程序路徑,默認uploadify.php
postData:傳遞參數,默認{}
auto:是否允許自動上傳文件,默認false
method:傳遞參數方式,默認post
外觀設置
width:按鈕寬度,默認120
height:按鈕高度,默認30
buttonClass:按鈕樣式設置,如:樣式爲.btnClass{color:red;}
buttonCursor:鼠標移入時指針樣式,默認hand,(注:設置後不知道怎麼顯示)
buttonImage:按鈕顯示圖片地址,默認false,(注:必須是高度2倍,包含兩個按鈕圖片,上默認、下鼠標移入,IE9)
buttonText:按鈕顯示文字信息,默認SELECT FILES,(注:3.0.0版本支持中文)
cancelImage:取消選中文件圖片,默認uploadify-cancel.png
fileTypeDesc:選擇文件時文件類型提示,默認All Files (*.*)
fileTypeExts:選擇文件時文件類型限制,默認*.*,(注:如果fileTypeDesc和fileTypeExts同時設置,則顯示組合,如:All Files (*.*) (*.*)
多個類型如:“*.JPG;*.GIF;*.PNG;*.BMP”)
操作設置
queueID:上傳隊列容器ID,默認false
removeCompleted:是否刪除容器內已經上傳完畢文件,默認true
removeTimeout:刪除容器內已經上傳完畢文件延遲時間,單位s,默認3
fileSizeLimit:設置允許上傳文件大小,單位k,默認0不限制
multi:是否支持多文件同時上傳,默認false
queueSizeLimit:限制一次上傳文件個數,即容器內最多文件個數,默認999
simUploadLimit:允許同時上傳文件個數,同時執行,默認1,(注:3.0.0測試版註釋此參數)
調試設置
debug:是否顯示調試框,默認false
checkExisting:檢查待上傳文件是否存在程序,默認uploadify-check-existing.php
其他設置
fileObjName:設置一個名字,在服務器處理程序中根據該名字來取上傳文件的數據,默認Filedata,(作用不明)
requeueErrors:未知,默認false
preventCaching:未知,默認true
progressData:未知,默認percentage
successTimeout:未知,默認30
transparent:未知,默認true
uploadLimit:未知,默認999
uploaderType:未知,默認html5
langFile:錯誤提示文件,可以忽略
id:當前操作的ID編碼,默認jQuery(this).attr('id'),可以忽略。
onClearQueue: function () {}:未知
onDialogOpen: function () {}:打開選擇文件窗口
onDialogClose: function () {}:關閉選擇文件窗口
onInit: function () {}:初始化
onQueueComplete: function () {}:全部文件上傳結束
onSelectError: function () {}:選擇文件:選擇錯誤
onSelect: function () {}:單個文件:選擇文件,每選中一個文件都執行一次
onSWFReady: function () {}:未知
onUploadCancel: function () {}:未知
onUploadComplete: function () {}:單個文件上傳結束,注意:最後一個文件結束在全部結束後
onUploadError: function () {}:上傳文件錯誤/取消已選擇文件
onUploadProgress: function () {}:單個文件:上傳過程中
demo 下載,有問題大家可以一起討論啊。。。。。