既認準這條路,又何必在意要走多久
阿新 • • 發佈:2019-02-09
自己遇到這樣的東西 先大概寫了一個模型
用的swfupload+struts
或者單獨的 swfupload +serverlet
檔案在程式中的位置具體如下:
必須的包:lib裡面的包都是必須的。
索要引用的js 有 jquery和 handlers(主要就是控制檔案上傳的一些js)和swfupload 和一個必要的flash swupload 這些 官網都有地址是:swfupload。裡面也有詳細的講解。
先說 struts的這一種,現在用struts的比較多:
首先建立 Uploadfile檔案
package com; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Timestamp; import javax.servlet.ServletContext; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadFile extends ActionSupport { private String message ; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } private File files; private String filesFileName; private String filesContentType ; public File getFiles() { return files; } public void setFiles(File files) { this.files = files; } public String getFilesFileName() { return filesFileName; } public void setFilesFileName(String filesFileName) { this.filesFileName = filesFileName; } public String getFilesContentType() { return filesContentType; } public void setFilesContentType(String filesContentType) { this.filesContentType = filesContentType; } public String getInfo(){ setMessage("linlin"); return SUCCESS; } /**** * swf上傳. 檔名字沒有改變 */ public String swfUpload1() throws Exception { // 實現上傳 InputStream is = new FileInputStream(files); /**獲取路徑**/ String root =ServletActionContext.getServletContext().getRealPath(""); /**分隔符**/ String separator = java.io.File.separator; /**儲存路徑**/ String path = root+separator+"upload" +separator+"file"+separator; System.out.println("---上傳檔案地址---"+path); //獲取時間戳 long time = System.currentTimeMillis(); File deskFile = new File(root, this.getFilesFileName()); System.out.println("--檔名字--"+this.getFilesFileName()); OutputStream os = new FileOutputStream(deskFile); byte[] bytefer = new byte[1024]; int length = 0; while ((length = is.read(bytefer)) != -1) { os.write(bytefer, 0, length); } os.close(); is.close(); return "success"; } /**** * 使用FileUtils.copyFile的上傳 * @return */ public String loadFile(){ /**當前時間戳**/ Timestamp currentTime = new Timestamp(System.currentTimeMillis()); ServletContext servletContext = ServletActionContext.getServletContext(); /**獲取路徑**/ String dataDir = servletContext.getRealPath(""); long time = System.currentTimeMillis(); /**分隔符**/ String separator = java.io.File.separator; /**判斷上傳檔案是否為空**/ if(null == files){ /**若檔案為空 則 報錯**/ return "檔案為空!"; }else{ // 判斷資料是否正確 // 檔案字尾名 int index = StringUtils.lastIndexOf(filesFileName, '.'); if (index == -1) { return "檔案型別錯誤!"; } /**獲取檔案字尾名**/ String extFileName = StringUtils.substring(filesFileName, index + 1); /**定義上傳位置**/ String path = dataDir+separator+"upload" +separator+"file"+separator; System.out.println("---檔案上傳位置---"+path); /**使用當前時間戳,避免檔案重複被覆蓋**/ String name = time+""; String filename = path + name + "." + extFileName.toLowerCase();; System.out.println("---檔名稱---"+name); File destFile = new File(filename); try { /**上傳檔案 用FileUtils**/ FileUtils.copyFile(files, destFile); } catch (IOException e) { e.printStackTrace(); return "附件上傳失敗!"; } } return SUCCESS; } /**** * * 使用IO 流 * @return * @throws IOException */ public String swfUpload() throws IOException{ if(null == files){ /**若檔案為空 則 報錯**/ return "檔案為空!"; }else{ // 判斷資料是否正確 // 檔案字尾名 int index = StringUtils.lastIndexOf(filesFileName, '.'); if (index == -1) { return "檔案型別錯誤!"; } /**獲取檔案字尾名**/ String extFileName = StringUtils.substring(filesFileName, index + 1); /**分隔符**/ String separator = java.io.File.separator; /**定義上傳位置**/ String root =ServletActionContext.getServletContext().getRealPath(""); String path = root+separator+"upload" +separator+"file"+separator; System.out.println("---檔案上傳位置---"+path); /**使用當前時間戳,避免檔案重複被覆蓋**/ long time = System.currentTimeMillis(); String name = time+""; String filename = path + name + "." + extFileName.toLowerCase(); File deskFile = new File(filename); System.out.println("---檔名稱---"+name); InputStream is = new FileInputStream(files); OutputStream os = new FileOutputStream(deskFile); byte[] bytefer = new byte[1024]; int length = 0; while ((length = is.read(bytefer)) != -1) { os.write(bytefer, 0, length); } os.close(); is.close(); return "success"; } } }
struts.xml的配置:
<package name="uploadfile" extends="struts-default" namespace="/"> <action name="getinfo" class="com.UploadFile" method="getInfo"> <result name="success">/upload.jsp</result> </action> <action name="uploadfile" class="com.UploadFile" method="loadFile"> <result name="success">/upload.jsp</result> </action> <action name="swfuploadfile" class="com.UploadFile" method="swfUpload"> <result name="success">/upload.jsp</result> </action> <!--刪除附件--> <action name="deletefile" class="com.deletFile" method="delFile"> <result name="success">/upload.jsp</result> </action> </package>
上傳頁面
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' 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="styles.css"> --> </head> <script type="text/javascript" src="swfupload/swfupload.js"></script> <script type="text/javascript" src="swfupload/handlers.js"></script> <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script> <body style="font-size: 12px;"> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ upload_url: "swfuploadfile.action" //上傳檔案需要請求的url, // File Upload Settings file_size_limit : "50 MB", // 1000MB file_types : "*.*",//設定可上傳的型別 file_types_description : "所有檔案", file_upload_limit : "10", file_post_name: "files",//相當於頁面的name屬性 file_queue_error_handler : fileQueueError,//選擇檔案後出錯 file_dialog_complete_handler : fileDialogComplete,//選擇好檔案後提交 file_queued_handler : fileQueued, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // Button Settings button_image_url : "images/SmallSpyGlassWithTransperancy_17x18.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 100, button_height: 18, button_text : '<span class="button">新增附件</span>', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 0, button_text_left_padding: 18, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, // Flash Settings flash_url : "swfupload/swfupload.swf", custom_settings : { upload_target : "divFileProgressContainer" }, // Debug Settings debug: false //是否顯示除錯視窗 }); }; function startUploadFile(){ swfu.startUpload(); } </script> <!-- --> <span id="spanButtonPlaceholder"></span> <div id="divFileProgressContainer" style="width:200;display:none;"></div> <div id="thumbnails"> <table id="infoTable" border="0" width="50%" style="border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;margin-top:8px;"> </table> </div> </body> </html>
這個效果是這樣的選擇一個檔案自動上傳一個檔案:
然後 可以一次性選擇完進行上傳:
swfUpload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' 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="styles.css">
-->
</head>
<script type="text/javascript" src="swfupload/swfupload.js"></script>
<script type="text/javascript" src="swfupload/handlers.js"></script>
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<body style="font-size: 12px;">
<script type="text/javascript">
var swfu;
var index = 1;
window.onload = function () {
swfu = new SWFUpload({
upload_url: "swfuploadfile.action",//要請求的action名字
// File Upload Settings
file_size_limit : "50 MB", // 1000MB
file_types : "*.*",//設定可上傳的型別
file_types_description : "所有檔案",
file_upload_limit : "10",
//上傳檔案的名稱
file_post_name: "files",//相當於頁面的name屬性
file_queue_error_handler : fileQueueError,//選擇檔案後出錯
file_dialog_complete_handler : fileDialogComplete,//用於處理選擇檔案後出發的事件
file_queued_handler : fileQueued,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,//上傳檔案失敗觸發的事件
upload_success_handler : uploadSuccess,//上傳檔案成功觸發的事件
upload_complete_handler : uploadComplete,//用於處理檔案上傳結束之後的事件
// Button Settings
button_image_url : "images/SmallSpyGlassWithTransperancy_17x18.png",//指向button圖片額的地址
button_placeholder_id : "spanButtonPlaceholder",//button的iD
button_width: 100,//button的寬度
button_height: 18,//button的高度
button_text : '<span class="button">新增附件</span>',//button裡面的文字
button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',
button_text_top_padding: 0,
button_text_left_padding: 18,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
// Flash Settings
flash_url : "swfupload/swfupload.swf",//flash的地址
custom_settings : {
upload_target : "divFileProgressContainer"
},
// Debug Settings
debug: false //是否顯示除錯視窗
});
};
function uploadComplete(file){//continue to upload next file
swfu.startUpload();
}
function fileDialogComplete(numFilesSelected ,numFilesQueued,numFilesinQueue){
var table = document.getElementById("filesTable");
table.style.display="block";
}
function fileQueued(file){
var table = document.getElementById("filesTable");
var row = table.insertRow();
var col1= row.insertCell();
var col2= row.insertCell();
var col3= row.insertCell();
var col4= row.insertCell();
row.id = file.id;
col4.id=index;
col1.innerHTML = file.name;
col2.innerHTML = file.size;
col3.innerHTML = showStatus(file.filestatus);
col4.innerHTML = "<input type='button' value = '刪除'onclick='deleteRow("+index+")'/>";
index++;
}
function showStatus(status){
var word ;
switch(status){
case SWFUpload.FILE_STATUS.QUEUED:
word="queued";
break;
case SWFUpload.FILE_STATUS.ERROR:
word="ERROR";
break;
case SWFUpload.FILE_STATUS.COMPLETE:
word="COMPLETE";
break;
}
return word;
}
function uploadSuccess(file){
var row = document.getElementById(file.id);
row.cells[2].innerHTML=showStatus(file.filestatus);
}
function uploadError(file){
var row = document.getElementById(file.id);
row.cells[2].innerHTML=showStatus(file.filestatus);
}
function startUploadFile(){
swfu.startUpload();
}
function deleteRow(obj) {
var x=document.getElementById(obj);
x.parentNode.parentNode.removeChild(x.parentNode);
}
</script>
<!-- -->
<span id="spanButtonPlaceholder"></span>
<div >
<table id="filesTable" border="0" width="50%" style="display: none">
<tr>
<td>name</td>
<td>size</td>
<td>status</td>
<td>del</td>
</tr>
</table>
<div>
<button onclick="startUploadFile()">上傳</button>
</body>
</html>
效果是這樣的:
然後點選上傳 一次性上傳這些檔案,其實 看上去是一次性上傳的,其實是一個一個激動上傳的,等於是系統自動呼叫了後臺三次。
刪除以後再說,