java實現批量上傳(swfupload)


下載 swfupload 文件夾 里面包含handlers.js,swfupload.js,swfupload.swf 三個文件。

我的是和ssh項目整合在一起的。因為struts2的攔截器會攔截所有請求,在跳轉到上傳文件的servlet中時request請求會被轉換為struts的請求。所以要去掉struts的請求。

假如web.xml配置的攔截所有請求,可以修改這里,不攔截所有

<filter>
        <filter-name>struts2</filter-name>
        <filter-class>
            org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>
                struts-default.xml,struts-plugin.xml,resources/struts/struts.xml
            </param-value>
        </init-param>
        <init-param>
            <param-name>actionPackages</param-name>
            <param-value>com.yuncai.modules</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

或者在struts.xml中加上 <constant name="struts.action.excludePattern" value="/servlet/.*" />  struts不會攔截這個路徑下的所有

上傳文件的servlet的路徑

<struts>
    <!-- 開啟使用開發模式,詳細錯誤提示 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默認后綴名 -->
    <constant name="struts.action.extension" value="jsp" />
    <constant name="struts.action.excludePattern" value="/servlet/.*" />
    <!-- 指定每次請求到達,重新加載資源文件 -->
    <constant name="struts.i18n.reload" value="true" />
    <!-- 視圖標簽默認的視圖主題-->
    <constant name="struts.ui.theme" value="simple" />
    <!-- 國際化資源文件 -->
    <constant name="struts.custom.i18n.resources" value="globalMessages" />
    <!-- locale -->
    <constant name="struts.locale" value="zh_CN" />
    <!-- 指定資源編碼類型 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 生成URL時是否包含請求參數 -->
    <constant name="struts.url.includeParams" value="none" />
    <!-- 文件上傳中整個請求內容允許的最大字節數 -->
    <constant name="struts.multipart.maxSize" value="1048576000" />
    
    <constant name="struts.objectFactory" value="spring"/>
  
</struts>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<head>
    <link rel="stylesheet" type="text/css" href="../css/zlstyle.css">
     <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.10.2.min.js"></script>
</head>
<body leftmargin="10" topmargin="10" marginwidth="10" marginheight="10">
        <table width="100%" border="1" bordercolor="#464646" align="center"
            cellpadding="0" cellspacing="0">        
                <tr>
                    <td align="right">
                        是否顯示:
                    </td>
                    <td>
                        <input type="checkbox" id="isValid" value="0" onclick="check1();"/>
                    </td>
                </tr>
                <tr>
                    <td align="right">
                        說明:
                    </td>
                    <td>
                        <textarea rows="" cols="" id="info"></textarea>
                    </td>
                </tr>
        </table>
        <input type="button" onclick="swfupload();" value="添加控件"/>
        <span id="spanButtonPlaceholder"></span>
        <div id="divFileProgressContainer" style="width:200;display:none;"></div>
        <div id="thumbnails">
            <table id="infoTable" border="0" style="background-color: #C5D9FF;"></table>
        </div>
<!--為了把表單數據傳到servlet,所以多加了一個點擊按鈕-->
<script type="text/javascript"> var swfu; function swfupload() { swfu = new SWFUpload({ upload_url: "/servlet/FileUploadServlet", // File Upload Settings file_size_limit : "50 MB", // 1000MB file_types : "*.apk",//設置可上傳的類型 file_types_description : "所有文件", file_upload_limit : "100", // 向服務端傳遞的參數 use_query_string : true, post_params: { "isValid" : document.getElementById("isValid").value,"info" : document.getElementById("info").value }, 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">選擇APK</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(); } function check1(){ var isValid = document.getElementById("isValid").value; if(isValid==0) document.getElementById("isValid").value="1"; else document.getElementById("isValid").value="0"; }</script> </body>
package com.yuncai.modules.servlet;


import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apkinfo.api.GetApkInfo;
import org.apkinfo.api.domain.ApkInfo;


import com.oreilly.servlet.MultipartRequest;
import com.yuncai.core.tools.DBConn;
import com.yuncai.core.tools.HttpOut;
import com.yuncai.core.tools.LogUtil;
import com.yuncai.core.util.DBHelper;
import com.yuncai.core.util.DBUpload;

/**
 * @author gx
 * @version 2014-4-3
 */
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = -3096800116651263134L;

    private String fileSizeLimit;

    public void init(ServletConfig config) throws ServletException {
        this.fileSizeLimit = config.getInitParameter("fileSizeLimit");
    }

    public void destroy() {
        super.destroy();
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String uploadDir = "upload" + File.separatorChar + "apk" + File.separatorChar;
        String ctxDir = session.getServletContext().getRealPath(String.valueOf(File.separatorChar));
        if (!ctxDir.endsWith(String.valueOf(File.separatorChar))) {
            ctxDir = ctxDir + File.separatorChar;
        }
        File savePath = new File(ctxDir + uploadDir);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        String saveDirectory = ctxDir + uploadDir;
        int maxPostSize = 80 * 1024 * 1024;
        String encoding = "UTF-8";
        MultipartRequest multi = null;
        try {
            multi = new MultipartRequest(request, saveDirectory, maxPostSize, encoding);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        Enumeration<?> files = multi.getFileNames();
        while (files.hasMoreElements()) {
            String name = (String) files.nextElement();
            File f = multi.getFile(name);
            if (f != null) {
             
                Connection conn = DBConn.getConn("sqlServer");
                String sql ="";
                PreparedStatement ps=null;
                sql = "select ID from T_Channel where NAME=?";
                ResultSet rs =null;
try {
                    conn = DBConn.getConn("sqlServer");
                    sql ="insert into table(isValid,info)  values(?,?)";
                    ps=conn.prepareStatement(sql);
                  
                    ps.setString(2, request.getParameter("info"));
                    ps.setString(1, request.getParameter("isValid"));
                    ps.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                }finally{
                        try {
                            if(DBHelper.isNoNull(ps))
                                ps.close();
                            if(DBHelper.isNoNull(conn))
                                conn.close();
                        } catch (SQLException e) {
                        }
                }
            }
        }

        
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    public String getFileSizeLimit() {
        return fileSizeLimit;
    }

    public void setFileSizeLimit(String fileSizeLimit) {
        this.fileSizeLimit = fileSizeLimit;
    }

}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM