JAVA版-SWFUpload使用(包括傳參問題) – JAVA編程語言程序開發技術文章

官方的版本中隻有php的版本,從網上找瞭其他人寫的內容,自己實現瞭一個servlet的版本,
但是又出現另一個問題,如何向後臺傳遞參數的問題,現在整理出來,以備忘。
問題:
1、編碼問題,做的示例用的gb18030,所以後臺很多的轉碼問題,采用UTF-8,能好一些,
2、傳遞中文問題,最好還是前臺進行encoding,(encodeURI),後臺進行解析取出來吧--未測試

上代碼:
一、前臺頁面index.jsp

001
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
002
 
003
<%
004
String path = request.getContextPath();
005
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
006
%>
007
 
008
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
009
<html>
010
  <head>
011
    <base href="<%=basePath%>">
012
    
013
    <title>文件上傳swfupload使用</title>
014
    <meta http-equiv="pragma" content="no-cache">
015
    <meta http-equiv="cache-control" content="no-cache">
016
    <meta http-equiv="expires" content="0">  
017
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
018
    <meta http-equiv="description" content="This is my page">
019
    <!–
020
    <link rel="stylesheet" type="text/css" href="styles.css">
021
    –>
022
    <link href="<%=basePath%>css/default.css" rel="stylesheet" type="text/css" />
023
    <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.js"></script>
024
    <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.queue.js"></script>
025
    <script type="text/javascript" src="<%=basePath%>js/fileprogress.js"></script>
026
    <script type="text/javascript" src="<%=basePath%>js/handlers.js"></script>
027
    
028
    
029
    <script type="text/javascript">
030
    var swfu;
031
 
032
    SWFUpload.onload = function () {
033
        var settings = {
034
            flash_url : "<%=basePath%>swfupload/swfupload.swf",
035
            flash9_url : "<%=basePath%>swfupload/swfupload_fp9.swf",
036
            upload_url: "<%=basePath%>upload",
037
            post_params: {
038
                "hello" : "Here I Am",
039
                "name" : "張三"
040
            },
041
            file_size_limit : "100 MB",
042
            file_types : "*.*",
043
            file_types_description : "All Files",
044
            file_upload_limit : 100,
045
            file_queue_limit : 0,
046
            custom_settings : {
047
                progressTarget : "fsUploadProgress",
048
                cancelButtonId : "btnCancel"
049
            },
050
            debug: true,
051
            use_query_string : true,//要傳遞參數,必須配置,可以從後臺取到參數,應該還有其他方式,如post方式,未瞭解
052
            
053
            // Button Settings
054
            button_image_url : "<%=basePath%>images/TestImageNoText_65x29.png",
055
            button_placeholder_id : "spanButtonPlaceholder",
056
            button_width: 61,
057
            button_height: 22,
058
            button_text: '瀏覽',
059
            button_text_style: ".spanButtonPlaceholder { font-size: 12; }",
060
            button_text_left_padding: 12,
061
            button_text_top_padding: 3,
062
 
063
            // The event handler functions are defined in handlers.js
064
            //swfupload_preload_handler : preLoad,
065
            //swfupload_load_failed_handler : loadFailed,
066
            file_queued_handler : fileQueued,
067
            file_queue_error_handler : fileQueueError,
068
            file_dialog_complete_handler : fileDialogComplete,
069
            upload_start_handler : uploadStart,
070
            upload_progress_handler : uploadProgress,
071
            upload_error_handler : uploadError,
072
            upload_success_handler : uploadSuccess,
073
            upload_complete_handler : uploadComplete,
074
            queue_complete_handler : queueComplete  // Queue plugin event
075
            
076
        };
077
 
078
        swfu = new SWFUpload(settings);
079
    }
080
    </script>
081
  </head>
082
  <body>
083
        <p class="fieldset flash" id="fsUploadProgress">
084
            <span class="legend">文件列表:</span>
085
            </p>
086
        <p id="pStatus">上傳瞭0個文件</p>
087
    
088
    <p class="flash" id="fsUploadProgress">
089
    </p>
090
    <p style="padding-left: 5px;">
091
        <span id="spanButtonPlaceholder"></span>
092
        <input id="btnCancel" type="button" value="取消" onclick="cancelQueue(upload);" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
093
    </p>
094
    
095
    <!– 上傳文件列表 –>
096
    <p class="fileList" id="fileList">
097
    </p>
098
    
099
  </body>
100
</html>
二、前臺接收後臺返回數據的位置 --handler.js-隻需要找到該位置,進行修改就可以瞭

01
function uploadSuccess(file, serverData) {
02
    try {
03
        var progress = new FileProgress(file, this.customSettings.progressTarget);
04
        progress.setComplete();
05
        progress.setStatus("上傳完成.");
06
        progress.toggleCancel(false);
07
        alert(serverData);
08
        
09
        //後臺傳遞回來的內容
10
        var serdata = document.getElementById("fileList");
11
        serdata.innerHTML = serverData;
12
        
13
    } catch (ex) {
14
        this.debug(ex);
15
    }
16
}
三、後臺servlet-Upload.java,下邊隻列出瞭用到的doPost()方法,其他內容都沒有變化

01
public void doPost(HttpServletRequest request, HttpServletResponse response)
02
            throws ServletException, IOException {
03
 
04
        //接收參數
05
        String hello = request.getParameter("hello");
06
        String name = request.getParameter("name");
07
        name = new String(name.getBytes("ISO-8859-1"),"UTF-8");//字符編碼問題,可以通過前臺encoding後臺再解析
08
        
09
        System.out.println("接收參數,hello="+hello+",name="+name);
10
    
11
        String path1 = request.getRequestURI()+"/files";
12
        System.out.println("____________request.getRequestURI():"+path1);
13
        String path2 = request.getSession().getServletContext().getRealPath("/");
14
        System.out.println("_________path2:"+path2);
15
    
16
        List<FileEntity> fileList;
17
        fileList = (List)request.getAttribute("fileList");
18
        if(fileList==null)
19
            fileList = new ArrayList<FileEntity>();
20
        
21
        //接收上傳文件
22
        String uploadSign = request.getParameter("upload");
23
          String rootPath = request.getParameter("rootPath");
24
          String path = request.getParameter("path");
25
          if(rootPath == null) rootPath = "";
26
            rootPath = rootPath.trim();
27
          if(rootPath.equals("")){
28
            //rootPath = application.getRealPath("/swfupload/files");//自由修改處二:指定服務器固定文件
29
              rootPath = path2+"/files";
30
          }
31
 
32
          if(path == null) {
33
            path = rootPath;
34
          }else{
35
            path = new String(Base64.decodeBase64(path.getBytes()));
36
          }
37
          System.out.println(path+"…path.getBytes():"+path.getBytes());
38
          uploadSign = "1";
39
          //上傳操作
40
          if(null != uploadSign && !"".equals(uploadSign)){
41
              FileItemFactory factory = new DiskFileItemFactory();
42
              ServletFileUpload upload = new ServletFileUpload(factory);
43
              //upload.setHeaderEncoding("UTF-8");
44
              try{
45
                  List items = upload.parseRequest(request);
46
                  if(null != items){
47
                      Iterator itr = items.iterator();
48
                      int i = 0;
49
                      while(itr.hasNext()){
50
                          FileItem item = (FileItem)itr.next();
51
                          FileEntity file = new FileEntity();//_____________________
52
                          if(item.isFormField()){
53
                              continue;
54
                          }else{
55
                              //自由修改處三:可修改上傳後的文件命名方式
56
                              SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");//以當前精確到秒的日期為上傳的文件的文件名
57
                              SimpleDateFormat sdd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
58
                              String type = item.getName().split("\\.")[1];//獲取文件類型
59
                              
60
                              System.out.println("——————————————————文件名稱:"+item.getName());
61
                              System.out.println("從GBK轉到UTF-8輸出:"+new String(item.getName().getBytes("GBK"),"UTF-8"));
62
                              
63
                              File savedFile = new File(path,sdf.format(new Date())+"."+type);
64
                              
65
                              //把文件放到列表中,在前臺顯示
66
                              System.out.println("__________________服務器上對應的文件名稱:"+sdf.format(new Date())+"."+type);
67
                              System.out.println("__________________完整路徑:"+path1+"/"+sdf.format(new Date())+"."+type);
68
                              file.setId(sdf.format(new Date()));
69
                              file.setDate(sdd.format(new Date()));
70
                              file.setFilename(item.getName());
71
                              file.setFilepath(path1+"/"+sdf.format(new Date())+"."+type);
72
                              file.setFilesize(item.getSize()+"");
73
                              file.setFiletype(type);
74
                              file.setMark("0");
75
                              fileList.add(file);
76
                              
77
                              item.write(savedFile);
78
                          }
79
                      }
80
                  }
81
              }catch(Exception e){
82
                  e.printStackTrace();
83
              }
84
          }
85
        
86
        
87
        response.setContentType("text/html");
88
        response.setCharacterEncoding("UTF-8");
89
        PrintWriter out = response.getWriter();
90
        if(fileList!=null){
91
            for(int i=0;i<fileList.size();i++){
92
                FileEntity file = (FileEntity)fileList.get(i);
93
                //out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",文件路徑:"+file.getFilepath());
94
                out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",上傳成功!");
95
            }
96
        }
97
    }
四、自定義的一個文件類FileEntity.java,測試時全部用的String類型

01
package com.swfupload.entity;
02
 
03
 
04
public class FileEntity {
05
    private String id;
06
    private String belong;
07
    private String filename;
08
    private String filepath;
09
    private String filetype;
10
    private String filesize;
11
    private String date;
12
    private String mark;
13
    
14
    public FileEntity(){}
15
    
16
    public String getId() {
17
        return id;
18
    }
19
    public void setId(String id) {
20
        this.id = id;
21
    }
22
    public String getBelong() {
23
        return belong;
24
    }
25
    public void setBelong(String belong) {
26
        this.belong = belong;
27
    }
28
    public String getFilename() {
29
        return filename;
30
    }
31
    public void setFilename(String filename) {
32
        this.filename = filename;
33
    }
34
    public String getFilepath() {
35
        return filepath;
36
    }
37
    public void setFilepath(String filepath) {
38
        this.filepath = filepath;
39
    }
40
    public String getFiletype() {
41
        return filetype;
42
    }
43
    public void setFiletype(String filetype) {
44
        this.filetype = filetype;
45
    }
46
    public String getFilesize() {
47
        return filesize;
48
    }
49
    public void setFilesize(String filesize) {
50
        this.filesize = filesize;
51
    }
52
    public String getDate() {
53
        return date;
54
    }
55
    public void setDate(String date) {
56
        this.date = date;
57
    }
58
    public String getMark() {
59
        return mark;
60
    }
61
    public void setMark(String mark) {
62
        this.mark = mark;
63
    }
64
    
65
    public static void main(String[] agrs){
66
        String str="";
67
        System.out.println(str);
68
    }
69
}
 

作者:itwarcraft
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *