fileinput上傳 全代碼包含後臺

說明:所提供的代碼採用原生servlet+jdbc不用考慮項目兼容性問題(java),考慮到通用性加入了fileinputconfig.properties配置文件,只須要拷貝代碼到項目中更改相關配置就能夠使用。javascript

一、先來效果圖(代碼在後面)css

初始化html

 

上傳前java

 

 

上傳後mysql

 

二、技術框架:fileinput + servlet+ jdbcjquery

  考慮到兼容全部的java框架因此採用了servlet+jdbc做爲後臺web

依賴的js+cssajax

<script type="text/javascript" charset="utf-8" src="../js/jquery-1.12.4.js"></script> <!-- jquery 儘可能不要使用過低的版本 -->
<script type="text/javascript" charset="utf-8" src="../js/bootstrap.min.js"></script><!-- bootstrap   -->
<script type="text/javascript" charset="utf-8" src="../js/fileinput.js"></script><!-- fileinput  -->
<script type="text/javascript" charset="utf-8" src="../js/zh.js"></script><!-- 國際化 漢化js  -->
<script type="text/javascript" charset="utf-8" src="../js/theme.js"></script><!-- 風格  -->


<link type="text/css" href="../css/bootstrap.css" rel="stylesheet"></link>
<link type="text/css" href="../css/fileinput.css" rel="stylesheet"></link>
<link type="text/css" href="../css/theme.css" rel="stylesheet"></link>

 

依賴的jar  這裏使用的mysql鏈接jar, 能夠根據本身的須要換成其餘的。沒有測試其餘的庫有沒有問題,若有問題自行解決。sql

 

三、上源碼(代碼皆由本人提供若有雷同純屬巧合)數據庫

頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello FileInput</title>
<style type="text/css"></style>
<!-- 插件依賴js -->
<script type="text/javascript" charset="utf-8" src="../js/jquery-1.12.4.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/fileinput.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/zh.js"></script>
<script type="text/javascript" charset="utf-8" src="../js/theme.js"></script>
<!-- 本身的js -->
<script type="text/javascript" charset="utf-8" src="../myjs/my.js"></script>
<!-- 插件依賴css -->
<link type="text/css" href="../css/bootstrap.css" rel="stylesheet"></link>
<link type="text/css" href="../css/fileinput.css" rel="stylesheet"></link>
<link type="text/css" href="../css/theme.css" rel="stylesheet"></link>

</head>
<body>
    <div style="height: 100%;width: 100%;margin-top: 50px;">
        <h1 style="text-align: center;">Hello FileInput</h1>
        <div>
            <div style="width: 400px;height: 500px;margin: 0 auto; ">
                <input type="file" name="upfile" id="upfile" class="file-loading" multiple="multiple">
            </div>
        </div>
    </div>
</body>
</html>

js

/** 文件上傳js  --典型的碼農 */
/** 重寫後臺方法需注意 文件上傳後臺Servlet 必須返回一個json  */

/**
 * 業務ID此處寫死 根據本身業務需求來定義
 * */
var bizid = "1001";
/**
 * 初始化fileinput
 * **/
var FileInput = function() {
    var oFile = new Object();
    // 初始化fileinput控件(第一次初始化)
    /**
     * 入參說明
     * ctrlName:控件ID值
     * uploadUrl:上傳地址
     * shwoKey:是否顯示上傳按鈕和上傳框 主要用於查看
     * imgPathArray:初始化數據path數組 主要用於查看和修改
     * imgNameArray:初始化數據name數組
     * **/
    oFile.Init = function(ctrlName, uploadUrl,shwoKey,imgPathArray,imgNameArray) {
        var control = $('#' + ctrlName);

        // 初始化上傳控件的樣式
        control.fileinput({
            'theme': 'explorer',
            language : 'zh', // 設置語言
            uploadUrl : uploadUrl, // 上傳的地址
            allowedFileExtensions : [ ],// 接收的文件後綴 例[*.jpg,*.png]
            showPreview:true,
            overwriteInitial: false,
            previewFileIcon: '<i class="fa fa-file"></i>',
            dropZoneEnabled: false,//是否顯示拖拽區域
            maxFileCount : 2, // 表示容許同時上傳的最大文件個數
            showUpload:false, //是否顯示上傳按鈕
            showRemove : false, //顯示移除按鈕
            showBrowse:shwoKey,//是否顯示選擇按鈕
            showCaption:shwoKey,//是否顯示選擇輸入框
            enctype : 'multipart/form-data',
            validateInitialCount : true,
            previewFileIcon :true,//是否顯示文件icon 默認圖片是直接顯示縮略圖 文件會展現相關內容
            msgFilesTooMany : "選擇上傳的文件數量({n}) 超過容許的最大數值{m}!",
            preferIconicPreview: true,//是否強制相關文件展現icon
            initialPreviewAsData: true,
            previewFileIconSettings: { //配置相關文件展現的icon
               
            },
           /*  uploadExtraData: function(previewId, index) {   //額外參數的關鍵點
               
            }, */
            initialPreview:imgPathArray,
            initialPreviewConfig: imgNameArray,
        });
    }
    return oFile;
};

/**
 * 插件初始化
 * 請求鏈接 根據實際狀況編寫
 * */
$(function(){
    var oFileInput = new FileInput();
    oFileInput.Init("upfile", "../fileinput.servlet?cmd=upload&bizid="+bizid,true,new Array(),new Array());
})
/**
 * 文件上傳後調用
 * */
$("#upfile").on("fileuploaded", function (event, data, previewId, index) {
    var obj = data.response;
    var deleleUrl ="../fileinput.servlet?cmd=delete&bizid="+bizid+"&id="+obj[0].id;    
    //$("#"+previewId).find(".kv-file-remove").attr("data-url",deleleUrl);
    $("#"+previewId).find(".kv-file-remove").click(function(){
        $.ajax({
            url : deleleUrl,
            type : "post",
            dataType:"json",
            success : function(result) {
                //成功操做
                
            },
            error : function(result) {
                //異常操做
                
            }
        });
        
    });
                
});


/**
 *   初始化fileinput數據 用於已上傳數據的插件 作編輯 查看使用
 *   bizid  父ID(業務id/分類id 根據需求自定義)用於批量查出同一類的文件 
 *   例:項目關聯多個圖片(文件) 查項目時須要查出全部的圖片 那麼項目和圖片的關係ID做爲父ID
 * */
function initFileInputData(bizid){
    var initUrl ="../fileinput.servlet?cmd=initFileInput&bizid="+bizid;    
    $.ajax({
        url : initUrl,
        type : "post",
        dataType:"json",
        success : function(result) {
            //成功操做
            var pathArr = new Array();//文件網絡地址 集合
            var nameArr = new Array();//文件信息集合
            $(result).each(function(){
                pathArr.push(this.path);//文件訪問地址 這裏須要網絡地址  例:http://localhost:8080/xxx/xx.jpg
                var obj = new Object(); 
                obj.caption=this.name;
                obj.size =this.size;
                obj.url = "../fileinput.servlet?cmd=delete&bizid="+bizid+"&id="+this.id;//用於初始化文件刪除事件地址
                nameArr.push(obj);
            });
            var oFileInput = new FileInput();
            oFileInput.Init("upfile", "../fileinput.servlet?cmd=upload&bizid="+bizid,true,pathArr,nameArr);
        },
        error : function(result) {
            //異常操做
        }
    });
}

function buttonSubmit(){
    $("#upfile").fileinput("upload");
}

 

後臺servlet

/**
 * fileInput
 */
package com.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSet;
import net.sf.json.JSONArray;

/**
 * 
 * @author 典型的碼農
 * @version $Id: FileUploadServlet.java, v 0.1 2017年7月20日 上午10:50:06
 */
public class FileUploadServlet extends HttpServlet {
    
    private static final long serialVersionUID = -1654876187842392874L;
    

    public FileUploadServlet() {   super();  }

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

    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException { }
    
    private Properties pro= new Properties();
    
    /**
     * 初始化時 獲取核心配置文件
     * */
    public void init() throws ServletException {
            pro = getUpConfig();
    }
    
    /**
     * post 請求
     * */
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        if("upload".equals( request.getParameter("cmd"))){
            upload(request,response);
        }else if("delete".equals( request.getParameter("cmd"))){
            delete(request,response);
        }else if("initFileInput".equals(request.getParameter("cmd"))){
            queryFileByPid(request,response);
        }
    }
    
    /**
     * 上傳
     * 注:fileinput 上傳每次只上傳一個文件  批量上傳時會屢次請求
     * */
    private void upload(HttpServletRequest request, HttpServletResponse response){
        try {
            //文件父ID(分類ID,業務ID)
            String bizid = request.getParameter("bizid");
            // 配置上傳參數
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 設置內存臨界值 - 超事後將產生臨時文件並存儲於臨時目錄中
            factory.setSizeThreshold(Integer.parseInt(pro.getProperty("memory.threshold")));
            // 設置臨時存儲目錄
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 設置最大文件上傳值
            upload.setFileSizeMax(Integer.parseInt(pro.getProperty("file.maxSize")));
            // 中文處理
            upload.setHeaderEncoding("UTF-8"); 
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
            // 構建文件保存目錄
            String uploadPath = pro.getProperty("file.uploadDir")+"/"+ sdf.format(new Date());
            // 若是目錄不存在則建立
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            // 解析請求的內容提取文件數據
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            String id = "";
            if (formItems != null && formItems.size() > 0) {
                // 迭表明單數據
                for (FileItem item : formItems) {
                    // 處理不在表單中的字段
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        //上傳
                        FileUtils.copyInputStreamToFile(item.getInputStream(),new File(uploadPath,fileName));
                        //上傳後保存
                        id = saveFileInfo(uploadPath+"/"+fileName,fileName,item.getSize()+"",bizid);
                    }
                }
            }
            ajax(response,id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 刪除文件數據
     * **/
    private void delete(HttpServletRequest request, HttpServletResponse response){
        try {
            String id = request.getParameter("id");
             //刪除文件
            deleteFile(id);
            String sql = "delete from "+pro.getProperty("table")+" where "+pro.getProperty("field.id")+"='"+id+"'";
            Connection conn = getConn();
            PreparedStatement pstmt;
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 刪除文件
     * */
    private void deleteFile(String id) throws Exception {
        String sql = "select * from "+pro.getProperty("table")+" where "+pro.getProperty("field.id")+"='"+id+"'";
        Connection conn = getConn();
        PreparedStatement pstmt;
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        //注意:此resulSet 來之mysql鏈接驅動包 跟換驅動時需注意 
        ResultSet rs =   (ResultSet) pstmt.executeQuery();
        while(rs.next()){ 
            String   filePath = rs.getString("F_PATH");
            File file = new File(filePath);
            file.delete();
        } 
        rs.close();
        pstmt.close();
        conn.close();
        
    }
    
    /**
     * 上傳後保存信息入庫
     * 注:根據實際入參需求 從新此方法
     * @param filePath ,fileName ,fileSize
     * @throws Exception 
     * @return uuid
     * */
    private String saveFileInfo(String filePath,String fileName,String fileSize,String bizid) throws Exception{
        UUID uuid = UUID.randomUUID();
        String sql = "insert into "+pro.getProperty("table")+"("+pro.getProperty("field.id")+","+pro.getProperty("field.path")+","+pro.getProperty("field.fileName")+","+pro.getProperty("field.size")+","+pro.getProperty("field.bizid")+") values('"+uuid+"','"+filePath+"','"+fileName+"','"+fileSize+"','"+bizid+"')";
        Connection conn = getConn();
        PreparedStatement pstmt;
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
        return uuid.toString();
    }
    /**
     * 根據父ID查詢文件
     * */
    private void queryFileByPid(HttpServletRequest request, HttpServletResponse response){
        try {
            String bizid = request.getParameter("bizid");
            String sql = "select * from "+pro.getProperty("table")+" where "+pro.getProperty("field.bizid")+"='"+bizid+"'";
            Connection conn = getConn();
            PreparedStatement pstmt;
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            //注意:此resulSet 來之mysql鏈接驅動包 跟換驅動時需注意 
            ResultSet rs =   (ResultSet) pstmt.executeQuery();
            List<Map<String, String>> resultList =  new ArrayList<Map<String,String>>();
            while(rs.next()){
                Map<String, String> map =  new HashMap<String, String>();
                map.put("id", rs.getString(pro.getProperty("field.id")));
                map.put("path", rs.getString(pro.getProperty("field.path")));
                map.put("name", rs.getString(pro.getProperty("field.fileName")));
                map.put("size", rs.getString(pro.getProperty("field.size")));
                resultList.add(map);
            } 
            rs.close();
            pstmt.close();
            conn.close();
            ajax(response,resultList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
    /**
     * 獲取上傳附件配置:上傳地址、文件大小、數據庫配置
     * @return Properties
     * 
     * */
    private Properties getUpConfig() {
        Properties prop = new Properties();
        try {
             // 返回Servlet上下文路徑。
            String path = this.getServletContext().getRealPath("/");
            // 在Servlet上下文路徑的最後包含一個"."號,因此這裏將它去除。
            path = path.substring(0, path.length() - 1);
            // 我將路徑放置在項目下的WEB-INF目錄下。
            path = path + "\\WEB-INF\\";
            // 這裏就是個人properties文件。
            path = path + "fileUploadConfig.properties";
            FileInputStream input = new FileInputStream(path);
            prop.load(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return prop;
    }
    /**獲取jdbc鏈接*/
    private Connection getConn() throws Exception {
        String driver = pro.getProperty("db.driver");
        String url = pro.getProperty("db.url");
        String username = pro.getProperty("db.username");
        String password = pro.getProperty("db.password");
        Connection conn = null;
        Class.forName(driver); //classLoader,加載對應驅動
        conn = (Connection) DriverManager.getConnection(url, username, password);
        return conn;
    }
    
    /**ajax 返回 注意上傳必須返回一個json*/
    public void ajax(HttpServletResponse response,String id){
         try {
            response.setContentType("application/json");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out= null;
            out = response.getWriter();
            Map<String, String> map =  new HashMap<String, String>();
            map.put("id", id);
            JSONArray  json = JSONArray.fromObject(map);
            out.print(json);
            out.flush();
            out.close();
         } catch (IOException e) {
             e.printStackTrace();
        }
     }
    
    /**ajax 返回 注意上傳必須返回一個json*/
    public void ajax(HttpServletResponse response,List<Map<String,String>> resultList){
         try {
            response.setContentType("application/json");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out= null;
            out = response.getWriter();
            JSONArray  json = JSONArray.fromObject(resultList);
            out.print(json);
            out.flush();
            out.close();
         } catch (IOException e) {
             e.printStackTrace();
        }
     }

}

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_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <!-- fileinput 上傳Servlet  -->
    <servlet>
        <servlet-name>FileInputServlet</servlet-name>
        <!-- 根據項目中此Servlet實際路徑編寫  -->
        <servlet-class>com.servlet.FileUploadServlet</servlet-class>
        <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
        <servlet-name>FileInputServlet</servlet-name>
        <url-pattern>/fileinput.servlet</url-pattern>
    </servlet-mapping>
</web-app>

 

核心配置fileinputconfig.properties

##上傳路徑
file.uploadDir=D:/upload/file
## 設置內存臨界值 - 超事後將產生臨時文件並存儲於臨時目錄中  單位kb
memory.threshold=3145728
##上傳文件大小 單位kb
file.maxSize=10485760

##數據庫配置
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://111.11.11.11:3306/plan?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=123456

##數據庫表配置
##表名
table=tbsys_adjunct

##必要字段 值對應數據庫字段
##主鍵
field.id=F_ID
##文件名稱
field.fileName=F_ORI_NAME
##文件大小
field.size=F_FILE_SIZE
##文件地址
field.path=F_PATH
##父id 關係外鍵(類別id/業務id)
field.bizid=F_FID

 

  完整項目源碼請點擊下載,可下載完整項目或在csdn搜索:fileinput+servlet+jdbc源碼

相關文章
相關標籤/搜索