要求:
- jQuery 1.4.x 或 更高
- Flash Player 9.0.24 或 更高
- 可以運行在服務端的開發語言,如PHP,ASP.NET或JAVA
前端實現:
1. 下載Uploadify Zip Package,它是免費的。
2. 解壓zip包,包中有如下文件:
jquery.uplodify-3.1.min.js
uplodify.php
uploadify.swf
uploadify.css
uploadify-cancel.png
check-exists.php(用於檢測文件是否已經存在)
3. 添加jquery支持
<script type="text/javascript" src="scripts/jquery-1.7.2.min.js"></script>
4. 添加uploadify的CSS文件到head標籤中
<link rel="stylesheet"type="text/css"href="css/uploadify.css"/>
5. 添加uploadify插件支持
<script type="text/javascript" src="scripts/jquery.uploadify-3.1.min.js"></script>
6. 添加dom結構到html文件中
<input type="file"name="file_upload"id="file_upload"/>
7. 添加如下代碼到</body>之前
<script type=”text/javascript”>
$(function() {
$('#file_upload').uploadify({
'swf' : 'flash/uploadify.swf', // 必須要有的,flash幫助我們與後端交互數據
'uploader' : 'uploadify/upload' // 處理文件上傳處理地址
// Put your options here // 其他參數
});
});
</script>
後端實現:
1. UploadServlet:該Sevlet會將上傳的文件存到項目下的store文件中,eclipse並不會存放在實際項目的store,而是存放到臨時項目的store中。
/**
* 處理文件上傳的post
* 下方的類名出自包import org.apache.commons.fileupload.*,開始搞錯了老是報錯
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
// Set factory constraints
//factory.setSizeThreshold(yourMaxMemorySize);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
boolean multipartContent = upload.isMultipartContent(request);
// Set overall request size constraint
//upload.setSizeMax(yourMaxRequestSize);
if(multipartContent) {
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
response.getWriter().print("success");
} else {
response.getWriter().print("file upload format is wrong!");
}
}
private void processUploadedFile(FileItem item) {
// Process a file upload
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
String storePath = this.getServletContext().getRealPath("/store");
File uploadedFile = new File(storePath + "/" + fileName);
if(!uploadedFile.exists()) {
try {
item.write(uploadedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void processFormField(FileItem item) {
// Process a regular form field
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
}}
2. checkExistSvl:
/**
* 檢測文件是否存在post
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// post中攜帶filename參數
String fileName = req.getParameter("filename");
String storePath = this.getServletContext().getRealPath("/store");
File file = new File(storePath + "/" + fileName);
// 存在返回1, 不存在返回0,處理由前端處理
if(file.exists()) {
res.getWriter().print("1");
} else {
res.getWriter().print("0");
}
}
3. web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MultiFileUpload</display-name>
<!-- 處理文件的Servlet -->
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.by.upload.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/uploadify/upload</url-pattern>
</servlet-mapping>
<!-- 處理檢查文件是否已經存在的Servlet -->
<servlet>
<servlet-name>checkExistSvl</servlet-name>
<servlet-class>com.by.upload.checkExistSvl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkExistSvl</servlet-name>
<url-pattern>/uploadify/checkExist</url-pattern>
</servlet-mapping>
<!-- 歡迎文件 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
項目的目錄結構圖:
uploadify屬性:src:服務端程序
css:樣式文件
flash:flash文件
img:圖片文件
scripts:腳本文件
store:存儲上傳文件,但是在eclipse中不會存放到這裏,而是存放到workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MultiFileUpload\store中
lib:使用apache提供的兩個jar包
index.jsp:主頁面
屬性名 |
說明 |
auto |
true|false:是否自動上傳文件 |
buttonClass |
添加瀏覽按鈕新樣式 |
buttonCursor |
arrow|hand:鼠標hover瀏覽時,處理效果,arrow明暗交替,hand手型 |
buttonImage |
新瀏覽按鈕的圖片地址 |
buttonText |
瀏覽按鈕新文本內容 |
checkExisting |
檢測文件是否存在的處理地址 |
debug |
true|false:是否啓用debug模式 |
fileObjName |
設置服務器端文件名稱,名稱存放在後端的item.getFieldName()中 |
fileSizeLimit |
限制上傳文件的大小,默認是KB |
fileTypeDesc |
上傳文件的描述 |
fileTypeExts |
限制上傳文件的類型,如*.jpg;*.png; |
formData |
附帶的其他參數key:value |
height |
瀏覽按鈕的高度,默認px |
itemTemplate |
提供了四個數值關於上傳的信息,並提供呈現html代碼 |
method |
post|get:指定get還是method方法 |
multi |
true|false:是否多文件上傳 |
overrideEvents |
Array:使哪些方法失效 |
preventCaching |
true|false:是否緩存一個random編碼,建議禁用 |
progressData |
percentage|speed:上傳進度顯示效果 |
queueID |
顯示上傳進度信息的區域ID |
queueSizeLimit |
number:限制區域內上傳文件的個數 |
removeCompleted |
true|false:上傳成功的文件是否隱藏 |
removeTimeout |
number:延遲幾秒刪除上傳成功的文件 |
requeueErrors |
true|false:當上傳出現error時,是否嘗試重新上傳 |
successTimeout |
number:文件成功後,延遲響應 |
swf |
swf路徑 |
uploader |
文件上傳處理地址 |
uploadLimit |
最大的上傳文件個數 |
width |
瀏覽按鈕的寬度 |
uploadify事件:
事件 |
說明 |
onCancel |
取消上傳文件時執行 |
onClearQueue |
當執行取消全部上傳文件時執行,$('#file_upload').uploadify('cancel','*'); |
onDestory |
禁用上傳功能時執行,$('#file_upload').uploadify('destory'); |
onDialogClose |
瀏覽對話框關閉時執行,函數包含如下參數: Arguments:queueData
|
onDialogOpen |
打開瀏覽對話框時執行,但效果等到關閉之後才能看到 |
onDisable |
禁用文件上傳公共時執行,$('#file_upload').uploadify('disable', true); |
onEnable |
啓用文件上傳功能時執行,$('#file_upload').uploadify('disable', false); |
onFallback |
flash不支持時執行 |
onInit |
初始化時執行 |
onQueueComplete |
所有文件被添加到上傳框中,無論成功還是取消操作,完成時執行,函數包括如下參數: Arguments : queueData
|
onSelect |
文件被選擇到對話框中時執行 |
onSelectError |
文件被選擇到對話框出現錯誤時執行,函數包含如下參數: Arguments:file
|
onSWFReady |
swf文件加載成功後執行 |
onUploadComplete |
每個文件成功加載到服務端時執行,函數包含如下參數: Arguments:file
|
onUploadError |
每個文件加載到服務端出現錯誤時執行,函數包含如下參數: Arguments:file
|
onUploadProgress |
當文件上傳進度變化時執行,函數如下參數: Arguments:file
|
onUploadStart |
文件上傳之前時執行,函數包括如下參數: Arguments:file
|
onUploadSuccess |
當文件成功上傳時執行,函數包含如下參數: Arguments:file |
uploadify方法:
方法 |
說明 |
cancel |
取消上傳文件 $('#file_upload').uploadify(‘cancel’, ‘fileId’); 或 $('#file_upload').uploadify(‘cancel’, ‘*’); |
destroy |
釋放uploadify實例,$('#file_upload').uploadify(‘destory’); |
disable |
啓用或禁用上傳功能 $('#file_upload').uploadify(‘disable’, true); 或 $('#file_upload').uploadify(‘disable’, false); |
settings |
設置或設置uploadify屬性值 $('#file_upload').uploadify(‘settings’, ‘buttonText’, ‘Changed’); 或 $('#file_upload').uploadify(‘settings’, ‘buttonText’); |
stop |
暫停上傳文件操作 $('#file_upload').uploadify(‘stop’); |
upload |
開始上傳文件操作 $('#file_upload').uploadify(‘upload’); |
代碼託管:
https://github.com/jason1213/Uploadify-Java