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+"/";
%>
  
        
    多张图片上传
	
	
	    
	
	
	

    

    

    

 
  
    
* 目前支持的上传格式 jpg,gif,bmp,png
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);
	}
%>



download









	



效果:上传成功后会传到工程里面的upload文件夹中

JavaScript/Jsp 多图上传和上传Excelx表到数据库_第1张图片

JavaScript/Jsp 多图上传和上传Excelx表到数据库_第2张图片JavaScript/Jsp 多图上传和上传Excelx表到数据库_第3张图片

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;i0){
					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中代码:

效果:

数据库中数据                                   Excel表中数据

JavaScript/Jsp 多图上传和上传Excelx表到数据库_第4张图片

你可能感兴趣的:(Java,Script)