fileinput上传 全代码包含后台
说明:所提供的代码采用原生servlet+jdbc不用考虑项目兼容性问题(java),考虑到通用性加入了fileinputconfig.properties配置文件,只需要拷贝代码到项目中更改相关配置就可以使用。
1、先来效果图(代码在后面)
初始化
上传前
上传后
2、技术框架:fileinput + servlet+ jdbc
考虑到兼容所有的java框架所以采用了servlet+jdbc作为后台
依赖的js+css
<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, 可以根据自己的需要换成其他的。没有测试其他的库有没有问题,如有问题自行解决。
3、上源码(代码皆由本人提供如有雷同纯属巧合)
页面
<%@ 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源码