• java-上传文件与现实上传文件


    项目结构:

    项目展示:

    数据库:

    /*
    SQLyog Ultimate v12.09 (64 bit)
    MySQL - 5.5.53 : Database - fileupload
    *********************************************************************
    */
    
    
    /*!40101 SET NAMES utf8 */;
    
    /*!40101 SET SQL_MODE=''*/;
    
    /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
    /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
    /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
    /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
    CREATE DATABASE /*!32312 IF NOT EXISTS*/`fileupload` /*!40100 DEFAULT CHARACTER SET utf8 */;
    
    USE `fileupload`;
    
    /*Table structure for table `fileupload` */
    
    DROP TABLE IF EXISTS `fileupload`;
    
    CREATE TABLE `fileupload` (
      `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
      `name` varchar(255) DEFAULT NULL COMMENT '产品名称',
      `path` varchar(255) DEFAULT NULL COMMENT '产品存储路径',
      `realname` varchar(255) DEFAULT NULL COMMENT '产品描述图片真实名称',
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
    
    /*Data for the table `fileupload` */
    
    insert  into `fileupload`(`id`,`name`,`path`,`realname`) values (20,'jack','/2017/8/16/cfd0d04e92714dcdb08c64c9db5fa638.jpg','jklh.jpg'),(21,'小米','/2017/8/16/72ee3800c2e44679a5df17a083f7759d.jpg','timg.jpg');
    
    /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
    /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
    /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
    /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
    

    -------------------------------

    代码:

    com.gordon.dao:

    --ProductDao.java

    package com.gordon.dao;
    
    import java.sql.SQLException;
    import java.util.List;
    
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    
    import com.gordon.domain.Product;
    import com.gordon.utils.DataSourceUtil;
    
    public class ProductDao {
    
    	/**
    	 * 添加产品
    	 * @param product_name
    	 * @param fileRealName
    	 * @param saveDbPath
    	 * @return
    	 * @throws SQLException 
    	 */
    	public int addProduct(String product_name, String fileRealName, String saveDbPath) throws SQLException {
    		QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
    		String sql = "INSERT INTO fileupload (name,realname, path) VALUES (?, ?, ?)";
    		return qr.update(sql, product_name, fileRealName, saveDbPath);
    	}
    
    	/**
    	 * 
    	 * @return
    	 * @throws SQLException 
    	 */
    	public List<Product> getAllProduct() throws SQLException {
    		QueryRunner qr = new QueryRunner(DataSourceUtil.getDataSource());
    		String sql = "select * from fileupload";
    		return qr.query(sql, new BeanListHandler<Product>(Product.class));
    	}
    
    }
    

    com.gordon.domain:
    --Product.java

    package com.gordon.domain;
    
    public class Product {
    	
    	private int id;
    	private String name;
    	private String realname;
    	private String path;
    
    	public Product() {
    	}
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getRealname() {
    		return realname;
    	}
    
    	public void setRealname(String realname) {
    		this.realname = realname;
    	}
    
    	public String getPath() {
    		return path;
    	}
    
    	public void setPath(String path) {
    		this.path = path;
    	}
    }
    

    com.gordon.service:
    --ProductService.java

    package com.gordon.service;
    
    import java.sql.SQLException;
    import java.util.List;
    
    import com.gordon.dao.ProductDao;
    import com.gordon.domain.Product;
    
    public class ProductService {
    
    	/**
    	 * 添加产品
    	 * @param product_name
    	 * @param fileRealName
    	 * @param saveDbPath
    	 * @return
    	 * @throws SQLException 
    	 */
    	public int addProduct(String product_name, String fileRealName, String saveDbPath) throws SQLException {
    		return new ProductDao().addProduct(product_name, fileRealName, saveDbPath);
    	}
    
    	/**
    	 * 获取所有商品
    	 * @return 
    	 * @throws SQLException 
    	 */
    	public List<Product> getAllProduct() throws SQLException {
    		return new ProductDao().getAllProduct();
    	}
    
    }
    

    com.gordon.utils:

    --DataSourceUtil.java

    package com.gordon.utils;
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.sql.DataSource;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class DataSourceUtil {
    	private static ComboPooledDataSource ds = new ComboPooledDataSource();
    
    	/**
    	 * 获取数据源
    	 * 
    	 * @return 连接池
    	 */
    	public static DataSource getDataSource() {
    		return ds;
    	}
    
    	/**
    	 * 获取连接
    	 * 
    	 * @return 连接
    	 * @throws SQLException
    	 */
    	public static Connection getConnection() throws SQLException {
    		return ds.getConnection();
    	}
    
    	/**
    	 * 释放资源
    	 * 
    	 * @param conn
    	 *            连接
    	 * @param st
    	 *            语句执行者
    	 * @param rs
    	 *            结果集
    	 */
    	public static void closeResource(Connection conn, Statement st, ResultSet rs) {
    		closeResultSet(rs);
    		closeStatement(st);
    		closeConn(conn);
    	}
    
    	/**
    	 * 释放连接
    	 * 
    	 * @param conn
    	 *            连接
    	 */
    	public static void closeConn(Connection conn) {
    		if (conn != null) {
    			try {
    				conn.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			conn = null;
    		}
    
    	}
    
    	/**
    	 * 释放语句执行者
    	 * 
    	 * @param st
    	 *            语句执行者
    	 */
    	public static void closeStatement(Statement st) {
    		if (st != null) {
    			try {
    				st.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			st = null;
    		}
    
    	}
    
    	/**
    	 * 释放结果集
    	 * 
    	 * @param rs
    	 *            结果集
    	 */
    	public static void closeResultSet(ResultSet rs) {
    		if (rs != null) {
    			try {
    				rs.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    			rs = null;
    		}
    
    	}
    }
    

    com.gordon.web.servlet:

    --AddProductServlet.java

    package com.gordon.web.servlet;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Calendar;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    import org.apache.commons.io.IOUtils;
    
    import com.gordon.service.ProductService;
    
    /**
     * 添加产品
     */
    @WebServlet("/addProduct")
    @MultipartConfig
    public class AddProductServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 1L;
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    
    		request.setCharacterEncoding("utf-8");
    
    		String product_name = request.getParameter("name");
    		Part part = request.getPart("file");
    
    		// 获取真实文件名称
    		String fileRealName = this.getFileRealName(part);
    
    		// 获取服务器上的绝对存储路径与数据库上的相对路径
    		String[] savePath = this.getSavePath(request, fileRealName);
    
    		int res = 0;
    		try {
    			// 上传文件
    			this.uploadFile(part, savePath[0]);
    
    			// 将数据存入数据库
    			res = new ProductService().addProduct(product_name, fileRealName, savePath[1]);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    		if (res != 1) {
    			request.setAttribute("msg", "添加文件失败!");
    			request.getRequestDispatcher("/error_page.jsp").forward(request, response);
    		}
    		
    		response.sendRedirect(request.getContextPath() + "/showProduct");
    	}
    
    	/**
    	 * 获取保存路径 [0] 服务器存储路径 [1]数据库存储路径
    	 * 
    	 * @param request
    	 * @param fileRealName
    	 * @return
    	 */
    	private String[] getSavePath(HttpServletRequest request, String fileRealName) {
    		// 获取存储时的随机产品名称
    		String randomFilePath = this.getRandomFileName(fileRealName);
    
    		// 获取存储绝对路径
    		String savepath = request.getServletContext().getRealPath("/upload");
    		// 获取存储目录 如:/2017/12/23/ 2017-12-23
    		String savedir = this.getSaveDir();
    
    		// 最终存储路径
    		String saveWebPosition = savepath + savedir;
    		String saveDbPosition = savedir;
    
    		// 服务器文件夹不存在则创建
    		File file = new File(saveWebPosition);
    		if (!file.exists()) {
    			file.mkdirs();
    		}
    
    		String[] res = { saveWebPosition + randomFilePath, saveDbPosition + randomFilePath };
    		return res;
    	}
    
    	/**
    	 * 获取存储目录
    	 * 
    	 * @return
    	 */
    	private String getSaveDir() {
    		Calendar now = Calendar.getInstance();
    		int year = now.get(Calendar.YEAR);
    		int month = now.get(Calendar.MONTH) + 1;
    		int day = now.get(Calendar.DAY_OF_MONTH);
    
    		return ("/" + year + "/" + month + "/" + day + "/").toString();
    	}
    
    	/**
    	 * 获取上传文件名称
    	 * 
    	 * @param part
    	 * @return
    	 */
    	private String getFileRealName(Part part) {
    		String contentDisposition = part.getHeader("Content-Disposition");
    		String filerealname = contentDisposition.substring(contentDisposition.lastIndexOf("filename="));
    		return filerealname.substring(10, filerealname.length() - 1);
    	}
    
    	/**
    	 * 上传文件
    	 * 
    	 * @param part
    	 */
    	private void uploadFile(Part part, String saveWebPath) throws Exception {
    		InputStream is = part.getInputStream();
    		FileOutputStream os = new FileOutputStream(saveWebPath);
    
    		IOUtils.copy(is, os);
    
    		is.close();
    		os.close();
    
    		part.delete();
    	}
    
    	/**
    	 * 获取随机产品名称
    	 * 
    	 * @param part
    	 * @return
    	 */
    	private String getRandomFileName(String fileRealName) {
    		String fileSuffix = fileRealName.substring(fileRealName.lastIndexOf("."));
    		String randomName = UUID.randomUUID().toString().replace("-", "").toLowerCase();
    		return randomName + fileSuffix;
    	}
    }
    

    --ShowProductServlet.java

    package com.gordon.web.servlet;
    
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.gordon.domain.Product;
    import com.gordon.service.ProductService;
    
    /**
     * 展示数据
     */
    @WebServlet("/showProduct")
    public class ShowProductServlet extends HttpServlet {
    
    	private static final long serialVersionUID = 1L;
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		
    		List<Product> list = null;
    		try {
    			list = new ProductService().getAllProduct();
    		} catch (SQLException e) {
    			e.printStackTrace();
    		}
    		
    		request.setAttribute("list", list);
    		request.getRequestDispatcher("/show_product.jsp").forward(request, response);
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    

    c3p0-config.xml

    <c3p0-config>
    	<!-- 默认配置,如果没有指定则使用这个配置 -->
    	<default-config>
    		<!-- 基本配置 -->
    		<property name="driverClass">com.mysql.jdbc.Driver</property>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/fileupload</property>
    		<property name="user">root</property>
    		<property name="password">root</property>
    	
    		<!--扩展配置-->
    		<property name="checkoutTimeout">30000</property>
    		<property name="idleConnectionTestPeriod">30</property>
    		<property name="initialPoolSize">10</property>
    		<property name="maxIdleTime">30</property>
    		<property name="maxPoolSize">100</property>
    		<property name="minPoolSize">10</property>
    		<property name="maxStatements">200</property>
    	</default-config> 
    	
    	
    	<!-- 命名的配置 -->
    	<named-config name="itcast">
    		<property name="driverClass">com.mysql.jdbc.Driver</property>
    		<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property>
    		<property name="user">root</property>
    		<property name="password">1234</property>
    		
    		
    		<!-- 如果池中数据连接不够时一次增长多少个 -->
    		<property name="acquireIncrement">5</property>
    		<property name="initialPoolSize">20</property>
    		<property name="minPoolSize">10</property>
    		<property name="maxPoolSize">40</property>
    		<property name="maxStatements">20</property>
    		<property name="maxStatementsPerConnection">5</property>
    	</named-config>
    </c3p0-config> 
    

    -------------------------------

    add_product.jsp

    <%@ 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>Insert title here</title>
    </head>
    <body>
    	<form action="${ pageContext.request.contextPath }/addProduct" method="post"
    		enctype="multipart/form-data">
    		<table>
    			<tr>
    				<td>产品名称:</td>
    				<td><input type="text" name="name" /></td>
    			</tr>
    			<tr>
    				<td>产品图片:</td>
    				<td><input type="file" name="file" /></td>
    			</tr>
    			<tr>
    				<td colspan="2"><input type="submit" value="添加产品" /></td>
    			</tr>
    		</table>
    	</form>
    </body>
    </html>
    

    error_page.jsp

    <%@ 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>Insert title here</title>
    </head>
    <body>
    	${ msg }
    </body>
    </html>
    

    index.jsp:

    <%@ 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>Insert title here</title>
    </head>
    <body>
    	<a href="${ pageContext.request.contextPath }/add_product.jsp">添加产品</a>
    </body>
    </html>
    

    show_product.jsp:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!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>Insert title here</title>
    </head>
    <body>
    	<table border="1">
    		<tr>
    			<td>id</td>
    			<td>产品名称</td>
    			<td>产品展示</td>
    		</tr>
    
    		<c:forEach var="p" items="${ list }">
    			<tr>
    				<td>${ p.id }</td>
    				<td>${ p.name }</td>
    				<td><img alt="" width="100" height="100" src="${ pageContext.request.contextPath}/upload${ p.path }"></td>
    			</tr>
    		</c:forEach>
    
    	</table>
    </body>
    </html>
    
  • 相关阅读:
    投票通过,PHP 8 确认引入 Union Types 2.0
    Laravel 菜鸟的晋级之路
    给公司写的composer包开发的规范
    Swoft 源码剖析
    听说PHP的生成器yield处理大量数据杠杠的
    读懂JWT的使用,你就会用PHP如何实现了
    python标准库及其它应用
    python常用算法题
    python迭代器实例
    python生成器实例
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/7374065.html
Copyright © 2020-2023  润新知