1. 程式人生 > >JavaScript/Jsp 多圖上傳和上傳Excelx表到資料庫

JavaScript/Jsp 多圖上傳和上傳Excelx表到資料庫

實現目標:利用MyEclipse/jsp/jquery多種知識完成Excel表的上傳和多圖的上傳。

1.多圖上傳

準備工作需要新增4個jar包和css樣式,imgs圖片,js樣式到工程裡面。

index程式碼:

<%@ page language="java" import="java.util.*" 
pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
  <head>
    <base href="<%=basePath%>">    
    <title>多張圖片上傳</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="css/dhtmlXVault.css" />

    <script language="JavaScript" type="text/javascript" src="js/dhtmlXVault.js"></script>

    <script language="JavaScript" type="text/javascript">
        var vault = null;
        function doOnLoad() {
            preLoadImages();
            vault = new dhtmlXVaultObject();
            vault.setServerHandlers("UploadHandler.jsp", "GetInfoHandler.jsp", "GetIdHandler.jsp");
            vault.create("vault1");
	}

	function preLoadImages(){
		var imSrcAr = new Array("btn_add.gif","btn_clean.gif","btn_upload.gif","ico_file.png","ico_image.png","ico_sound.png","ico_video.png","ico_zip.png","pb_back.gif","pb_demoUload.gif","pb_empty.gif");
		var imAr = new Array(0);
		for(var i=0;i<imSrcAr.length;i++){
			imAr[imAr.length] = new Image();
			imAr[imAr.length-1].src = "imgs/"+imSrcAr[i];
		}
	}
    </script>

    <style>
	body {font-size:12px}
	.{font-family:arial;font-size:12px}
	h1 {cursor:hand;font-size:16px;margin-left:10px;line-height:10px}
	xmp {color:green;font-size:12px;margin:0px;font-family:courier;background-color:#e6e6fa;padding:2px}
	.hdr{
		background-color:lightgrey;
		margin-bottom:10px;
		padding-left:10px;
	}
    </style>

</head> 
  <body onload="doOnLoad()">
    <div style="color:#ff0000;font-size:12px;">* 目前支援的上傳格式 jpg,gif,bmp,png</div>
    <div id="vault1"></div>  
  </body>
</html>
GetIdHeader程式碼:
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="com.scand.fileupload.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%
    String id =  request.getSession().getId().toString();
    out.println(id);
    session.setAttribute("FileUpload.Progress."+id,"0");
%>

GetInfoHeader程式碼:

<%
	out.println(session.getAttribute("FileUpload.Progress."
			+ request.getParameter("sessionId").toString().trim()));
%>

UploadHandler程式碼:

<%@ page import="org.apache.commons.fileupload.*" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="com.scand.fileupload.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%
	String uploadFolder = request.getRealPath("/" + "\\upload");

	// Check that we have a file upload request
	boolean isMultipart = FileUpload.isMultipartContent(request);

	if (!isMultipart) {

		out.println("Use multipart form to upload a file!");

	} else {

		String fileId = request.getParameter("sessionId").toString()
				.trim();

		//建立資料工廠
		FileItemFactory factory = new ProgressMonitorFileItemFactory(
				request, fileId);
		ServletFileUpload upload = new ServletFileUpload(factory);

		//從請求物件中獲得要上傳物件
		List /* FileItem */items = upload.parseRequest(request);

		//迭代所有上傳的FileItem
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();

			if (item.isFormField()) {
				//如果是表單物件再此處處理
			} else {
				//處理上傳檔案
				String fieldName = item.getFieldName();
				String fileName = item.getName();
				int i2 = fileName.lastIndexOf("\\");
				if (i2 > -1)
					fileName = fileName.substring(i2 + 1);
				File dirs = new File(uploadFolder);
				if (!dirs.exists()) {
					dirs.mkdir();
				}
				//dirs.mkdirs();
				long l = System.currentTimeMillis();
				String houzhui = fileName.substring(fileName
						.lastIndexOf("."));

				fileName = l + houzhui;
				if (houzhui.equals(".jpg") || houzhui.equals(".gif")
						|| houzhui.equals(".png")
						|| houzhui.equals(".bmp")
						|| houzhui.equals(".JPG")
						|| houzhui.equals(".GIF")
						|| houzhui.equals(".PNG")
						|| houzhui.equals(".BMP")) {
					File uploadedFile = new File(dirs, fileName);
					item.write(uploadedFile);
					session.setAttribute("FileUpload.Progress."
							+ fileId, "-1");
				} else {
					session.setAttribute("FileUpload.Progress."
							+ fileId, "-2");
				}
			}
		}
	}
%>
downLoad程式碼:
<%@page import="com.jspsmart.upload.SmartUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
	String fileName = request.getParameter("fileName");
	if (fileName != null) {
		fileName = fileName.replaceAll(basePath, "");
		SmartUpload su = new SmartUpload();
		su.initialize(pageContext);
		su.downloadFile(fileName);
	}
%>

<head>
<base href="<%=basePath%>">
<title>download</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">
<script type="text/javascript">
	function d1(obj) {
		window.location.href = "download.jsp?fileName=" + obj.src;
	}
</script>
</head>

<body>
	<form action="" name="baseForm">
		<img alt="" src="upload/1478057251961.jpg" name="zyf1"
			onclick="d1(this)"> <br> <img alt=""
			src="upload/1478057251961.jpg" name="zyf2"> <br> <img
			alt="" src="upload/1478057251961.jpg" name="zyf3"> <br>
	</form>
</body>
</html>

效果:上傳成功後會傳到工程裡面的upload資料夾中



2.將Excel表單上傳到資料庫中

DBConnection程式碼:

package com.jredu.excel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
	   private static Connection con = null;
	    
	   private static String driverName = "com.mysql.jdbc.Driver";
		
	   private static String userName   = "root";
		
	   private static String userPasswd = "ffffff";
		
	   private static String dbName     = "you";
		
	   private static String url = "jdbc:mysql://localhost/" + dbName 
		                        + "?user=" + userName 
		                        + "&password=" + userPasswd
		                        + "&useUnicode=true&characterEncoding=gbk";
    public static Connection getConnection(){
    	
    	try{
    		 Class.forName(driverName);
      	     con = DriverManager.getConnection(url);
    	}catch (Exception e) {
			e.printStackTrace();
		}
    	return con;
    }
    public static void closeConnection(){
    	if(con != null){
    		try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    }
}

demoSel程式碼:

package com.jredu.excel;

import java.io.IOException;
import java.io.PrintWriter;

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

public class demoSel extends HttpServlet {
	public demoSel() {
		super();
	}

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

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

	}

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

		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		System.out.println("匯入成功");
		// TestExcel.start();
	}

	public void init() throws ServletException {
	}

}

Excel實體類程式碼:

package com.jredu.excel;

public class Excel {

	private String id;
	private String name;
	private String className;
	private String sex;
	
	public Excel(){};
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
}

TestExcel程式碼:

package com.jredu.excel;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestExcel {

	 //記錄類的輸出資訊-
	//獲取Excel文件的路徑-
	 //.xlsx檔案用XSSFWorkbook   .xlx 用的HSSFWorkbook
	public static String filepath="C://Users/Administrator/Desktop/excel.xlsx";
	public static void start(String filepath){
		//建立對excel工作簿的引用
		XSSFWorkbook wookbook;
		try {
			wookbook = new XSSFWorkbook(new FileInputStream(filepath));
			//在Execl文件中,第一張工作表的預設索引是0
			//XSSFSheet sheet=wookbook.getSheetAt(0);
			XSSFSheet sheet=wookbook.getSheet("Sheet1");
			//獲取到Execl檔案中的所有行數-
			int rows=sheet.getPhysicalNumberOfRows();
			//遍歷行
			for(int i=1;i<rows;i++){
				//讀取左上端單元格
				XSSFRow row=sheet.getRow(i);
				//行不能空
				if(row!=null){
					//獲取到所有的列-
					int cells=row.getPhysicalNumberOfCells();
					String value="";
					//遍歷列-
					for(int j=0;j<cells;j++){
						//獲取列的值
						XSSFCell cell=row.getCell(j);
						if(cell!=null){
							switch(cell.getCellType()){
							//這個型別是:公式
							//Excel裡面的“公式”,可以用cell.getNumericCellValue(); 來獲得“結果”,也就是“公式”計算之後的結果 
							case HSSFCell.CELL_TYPE_FORMULA:
								break;
							//這個型別是:數字
							case HSSFCell.CELL_TYPE_NUMERIC:
								value+=cell.getNumericCellValue()+",";
								break;
							case HSSFCell.CELL_TYPE_STRING:
								value+=cell.getStringCellValue()+",";
								break;
								default:
									value +=0;
							}
						}
					}
					//將資料插入到mysql資料庫中
					String[] val=value.split(",");
					Excel entity=new Excel();
					entity.setId(val[0]);
					entity.setName(val[1]);
					entity.setClassName(val[2]);
					entity.setSex(val[3]);
					TestMethod method=new TestMethod();
					int a=method.add(entity);
					if(a>0){
					System.out.println("插入成功");
					}else{
						System.out.println("插入失敗");
					}			
				}
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
	}
}

TestMethod程式碼:

package com.jredu.excel;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestMethod {

	public int add(Excel te) {

		Connection con = DBConnection.getConnection();
		PreparedStatement pstmt = null;
		int count = 0;
		String sql = " insert into excel(id,name,className,sex) values(?,?,?,?)";
		try {
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, te.getId());
			pstmt.setString(2, te.getName());
			pstmt.setString(3, te.getClassName());
			pstmt.setString(4, te.getSex());
			count = pstmt.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			DBConnection.closeConnection();
		}
		return count;
	}
}

index中程式碼:

<form action="servlet/demoSel" method="post">
   <input type="submit" value="提交excle">
   </form>

效果:

資料庫中資料                                   Excel表中資料


相關推薦

JavaScript/Jsp Excelx資料庫

實現目標:利用MyEclipse/jsp/jquery多種知識完成Excel表的上傳和多圖的上傳。 1.多圖上傳 準備工作需要新增4個jar包和css樣式,imgs圖片,js樣式到工程裡面。 index程式碼: <%@ page language="java" im

Arcgis api for Javascript層查詢(

在使用arcgis for javascript api 進行地圖要素查詢的過程中,發現使用QueryTask查詢,單次只能查詢單個圖層;如果需要查詢多個圖層,就必須要新建多個QueryTask物件來

webuploader+springMvc+JSP 實現

<span style="font-family: Arial, Helvetica, sans-serif;"><div class="floor-popAd clearfix"></span> <span class

微信jssdk圖片,一張一張的 一次性好幾張

pla can 參數錯誤 其他 屬性 使用 down pop menu //html模板 <div class="zhaopin_3_2"> <div id="bbb"></div> &

使用eclipse自帶的git從githubclone專案

第一步:首先在GitHub上建立一個庫。 第二步:記住這個庫的URI 第三步:在eclipse中進入其git模式 第四步:選擇在git中clone一個庫 第五步:在彈出的對話方塊中貼上第二步中URI,這一步要輸入你的賬號密碼(此處略過) 第六步:GitH

ArcGIS API For Javascript層顯示與隱藏,層要素選框查詢

5、多圖層的載入與隱藏 利用Html+Javascript前端程式設計實現上傳到服務端的地圖服務中的多圖層的載入與隱藏。本實驗中除了底圖之外,添加了共10個圖層,分別為 賓館酒店_point (0) 餐飲_point (1) 超市商城_point (2) 地級市_font

一種快速簡便優秀的全域性曲線調整與區域性資訊想結合的非線性彩色增強演算法(深度分析探索)

  本文的分析基於《Adaptive and integrated neighborhood-dependent approach for nonlinear enhancement of color images》一文相關內容,但對其進行了深度的改良。   我們首先解讀或者說翻譯下這篇論文。   論文公佈的

iOS 使用AFN 進行單

圖片上傳時必要將圖片進行壓縮,不然會上傳失敗 1.單張圖上傳 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    [manager POST:urlStr

沒金幣了 簡潔的拍照

一、匯入 httpmine-4.3.5.jar   httpclient-4.3.5.jar 二、建立手機檔案目錄  將拍的照片路徑分成File新增到該目錄下 三、啟動系統相機 也可以自定義camera類對圖片進行處理 四、啟動子執行緒 生成客戶端傳送H

input file限制大小張數

    public Map<String, Object> upload(@RequestParam(value="file",required=false)MultipartFile[] file,        HttpServletRequest requ

JavaScript/Jsp 實現對資料庫的增刪改查簡單的下載檔案

完成目標:在頁面顯示資料庫的資訊,並且完成對資料庫的增刪改查,並且增加分頁功能。在頁面實現圖片或文字的下載。 1.增刪改查操作 User實體類程式碼: package com.jredu.web.entity; public class User { private

RootFramework框架實現文件讀取以及使用JavaScript獲取fields中的值

roo 讀取 frame get .get 轉換 script 輸入 tor 1、項目中使用的相對路徑需要轉換成絕對路徑,(Python方法實現 os.path.abspath(‘path‘)) 2、choose file [locators,file_pat

struts2學習(14)struts2文件下載(4)個文件下載

sym ring spl out urn ide http iso length 四、多個文件上傳: 五、struts2文件下載: 多個文件上傳action com.cy.action.FilesUploadAction.java: package com.cy.a

bootstrap file input 實現功能

slow customer dex event view 文件 all shee end 官方文檔 http://plugins.krajee.com/ demo http://plugins.krajee.com/file-input-ajax-demo/3

Thinkphp5

lena action val clas 錯誤 err each form files html代碼 <div class="content" id="content_list"> <!-- 上傳部分 -->

004-React-Native--選擇

conf ack 資料 multiple spa pac .get end ext 參考資料:http://www.jianshu.com/p/488e62ed9656 一:使用react-native-image-crop-picker進行圖片選擇時,並沒有提供

Vue的移動端插件vue-easy-uploader

ext gin ted log code 支持 使用 tip master 原文地址 前言 這段時間趕項目,需要用到多文件上傳,用Vue進行前端項目開發。在網上找了不少插件,都不是十分滿意,有的使用起來繁瑣,有的不能適應本項目。就打算自己折騰一下,寫一個Vue的上傳插件,一

tp5

html inf pic hidden download jquery 獲得 後臺 filetype 首先是最終的完成效果 這裏是源代碼下載地址 https://pan.baidu.com/s/1eSAQoSy 然後是具體的詳細步驟(圖片為網上參考,代碼是實際寫出效果

實現點擊單個圖片的

cells any cell sage cookie append toast its cin 這是一個通過接口實現上傳圖片,然後調用另一個接口統一提交的方法 結構 <div class="load-box"> <label for="b

【轉載】laravel中使用WangEditor及

1.2 sources views created select pic head 使用說明 token 1. 創建項目及安裝所需安裝包 1.1 創建項目 composer create-project laravel/laravel=5.3 blog_wangeditor