SWFUpload文件上傳服務器端采用Java接收

jopen 12年前發布 | 92K 次閱讀 SWFUpload 文件上傳

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

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

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>

<%
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>文件上傳swfupload使用</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">
    -->
    <link href="<%=basePath%>css/default.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.js"></script>
    <script type="text/javascript" src="<%=basePath%>swfupload/swfupload.queue.js"></script>
    <script type="text/javascript" src="<%=basePath%>js/fileprogress.js"></script>
    <script type="text/javascript" src="<%=basePath%>js/handlers.js"></script>


    <script type="text/javascript">
    var swfu;

    SWFUpload.onload = function () {
        var settings = {
            flash_url : "<%=basePath%>swfupload/swfupload.swf",
            flash9_url : "<%=basePath%>swfupload/swfupload_fp9.swf",
            upload_url: "<%=basePath%>upload",
            post_params: {
                "hello" : "Here I Am",
                "name" : "張三"
            },
            file_size_limit : "100 MB",
            file_types : "*.*",
            file_types_description : "All Files",
            file_upload_limit : 100,
            file_queue_limit : 0,
            custom_settings : {
                progressTarget : "fsUploadProgress",
                cancelButtonId : "btnCancel"
            },
            debug: true,
            use_query_string : true,//要傳遞參數,必須配置,可以從后臺取到參數,應該還有其他方式,如post方式,未了解

            // Button Settings
            button_image_url : "<%=basePath%>images/TestImageNoText_65x29.png",
            button_placeholder_id : "spanButtonPlaceholder",
            button_width: 61,
            button_height: 22,
            button_text: '瀏覽',
            button_text_style: ".spanButtonPlaceholder { font-size: 12; }",
            button_text_left_padding: 12,
            button_text_top_padding: 3,

            // The event handler functions are defined in handlers.js
            //swfupload_preload_handler : preLoad,
            //swfupload_load_failed_handler : loadFailed,
            file_queued_handler : fileQueued,
            file_queue_error_handler : fileQueueError,
            file_dialog_complete_handler : fileDialogComplete,
            upload_start_handler : uploadStart,
            upload_progress_handler : uploadProgress,
            upload_error_handler : uploadError,
            upload_success_handler : uploadSuccess,
            upload_complete_handler : uploadComplete,
            queue_complete_handler : queueComplete  // Queue plugin event

        };

        swfu = new SWFUpload(settings);
    }
    </script>
  </head>
  <body>
        <div class="fieldset flash" id="fsUploadProgress">
            <span class="legend">文件列表:</span>
            </div>
        <div id="divStatus">上傳了0個文件</div>

    <div class="flash" id="fsUploadProgress">
    </div>
    <div style="padding-left: 5px;">
        <span id="spanButtonPlaceholder"></span>
        <input id="btnCancel" type="button" value="取消" onclick="cancelQueue(upload);" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
    </div>

    <!-- 上傳文件列表 -->
    <div class="fileList" id="fileList">
    </div>

  </body>
</html>

二、前臺接收后臺返回數據的位置 --handler.js-只需要找到該位置,進行修改就可以了

function uploadSuccess(file, serverData) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("上傳完成.");
        progress.toggleCancel(false);
        alert(serverData);

        //后臺傳遞回來的內容
        var serdata = document.getElementById("fileList");
        serdata.innerHTML = serverData;

    } catch (ex) {
        this.debug(ex);
    }
}

三、后臺servlet-Upload.java,下邊只列出了用到的doPost()方法,其他內容都沒有變化

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //接收參數
        String hello = request.getParameter("hello");
        String name = request.getParameter("name");
        name = new String(name.getBytes("ISO-8859-1"),"UTF-8");//字符編碼問題,可以通過前臺encoding后臺再解析

        System.out.println("接收參數,hello="+hello+",name="+name);

        String path1 = request.getRequestURI()+"/files";
        System.out.println("____________request.getRequestURI():"+path1);
        String path2 = request.getSession().getServletContext().getRealPath("/");
        System.out.println("_________path2:"+path2);

        List<FileEntity> fileList;
        fileList = (List)request.getAttribute("fileList");
        if(fileList==null)
            fileList = new ArrayList<FileEntity>();

        //接收上傳文件
        String uploadSign = request.getParameter("upload");
          String rootPath = request.getParameter("rootPath");
          String path = request.getParameter("path");
          if(rootPath == null) rootPath = "";
            rootPath = rootPath.trim();
          if(rootPath.equals("")){
            //rootPath = application.getRealPath("/swfupload/files");//自由修改處二:指定服務器固定文件
              rootPath = path2+"/files";
          }

          if(path == null) {
            path = rootPath;
          }else{
            path = new String(Base64.decodeBase64(path.getBytes()));
          }
          System.out.println(path+"...path.getBytes():"+path.getBytes());
          uploadSign = "1";
          //上傳操作
          if(null != uploadSign && !"".equals(uploadSign)){
              FileItemFactory factory = new DiskFileItemFactory();
              ServletFileUpload upload = new ServletFileUpload(factory);
              //upload.setHeaderEncoding("UTF-8");
              try{
                  List items = upload.parseRequest(request);
                  if(null != items){
                      Iterator itr = items.iterator();
                      int i = 0;
                      while(itr.hasNext()){
                          FileItem item = (FileItem)itr.next();
                          FileEntity file = new FileEntity();//_____________________
                          if(item.isFormField()){
                              continue;
                          }else{
                              //自由修改處三:可修改上傳后的文件命名方式
                              SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddkkmmss");//以當前精確到秒的日期為上傳的文件的文件名
                              SimpleDateFormat sdd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                              String type = item.getName().split("\\.")[1];//獲取文件類型

                              System.out.println("——————————————————文件名稱:"+item.getName());
                              System.out.println("從GBK轉到UTF-8輸出:"+new String(item.getName().getBytes("GBK"),"UTF-8"));

                              File savedFile = new File(path,sdf.format(new Date())+"."+type);

                              //把文件放到列表中,在前臺顯示
                              System.out.println("__________________服務器上對應的文件名稱:"+sdf.format(new Date())+"."+type);
                              System.out.println("__________________完整路徑:"+path1+"/"+sdf.format(new Date())+"."+type);
                              file.setId(sdf.format(new Date()));
                              file.setDate(sdd.format(new Date()));
                              file.setFilename(item.getName());
                              file.setFilepath(path1+"/"+sdf.format(new Date())+"."+type);
                              file.setFilesize(item.getSize()+"");
                              file.setFiletype(type);
                              file.setMark("0");
                              fileList.add(file);

                              item.write(savedFile);
                          }
                      }
                  }
              }catch(Exception e){
                  e.printStackTrace();
              }
          }


        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        if(fileList!=null){
            for(int i=0;i<fileList.size();i++){
                FileEntity file = (FileEntity)fileList.get(i);
                //out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",文件路徑:"+file.getFilepath());
                out.println("文件:"+ new String(file.getFilename().getBytes("GBK"),"UTF-8")+",上傳成功!");
            }
        }
    }

四、自定義的一個文件類FileEntity.java,測試時全部用的String類型

package com.swfupload.entity;


public class FileEntity {
    private String id;
    private String belong;
    private String filename;
    private String filepath;
    private String filetype;
    private String filesize;
    private String date;
    private String mark;

    public FileEntity(){}

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getBelong() {
        return belong;
    }
    public void setBelong(String belong) {
        this.belong = belong;
    }
    public String getFilename() {
        return filename;
    }
    public void setFilename(String filename) {
        this.filename = filename;
    }
    public String getFilepath() {
        return filepath;
    }
    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }
    public String getFiletype() {
        return filetype;
    }
    public void setFiletype(String filetype) {
        this.filetype = filetype;
    }
    public String getFilesize() {
        return filesize;
    }
    public void setFilesize(String filesize) {
        this.filesize = filesize;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getMark() {
        return mark;
    }
    public void setMark(String mark) {
        this.mark = mark;
    }

    public static void main(String[] agrs){
        String str="";
        System.out.println(str);
    }
}

 


 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!