java 使用框架Spring MVC批量上传图片
运行环境:jdk1.8.0_17+tomcat 8 + spring:4.3.4+mybatis:3.2.7+ eclipse ide 2018+maven管理
最近写项目时候用到上传图片文件等功能之前写过没有总结,以及记录等,今天总结下写的批量上传图片功能
前段只需要把所有的选择的图片提交上来即可,后台会逐个处理,并且会在服务器或者当前电脑自己新建一个存放图片的文件夹,在application.properties配置里面你可以指定你所存放图片的路径,存图片的文件夹,缩略图的路径,以及缩略图的文件夹。
功能实现效果:
上传图片的Controller方法:
/** * 上传图片发布宝贝的控制器 * @return 图片缩略图imageList * @throws IOException * @throws FileNotFoundException */ @RequestMapping("/releaseBaby") public Object UploadPictree(@RequestParam("upload_file")CommonsMultipartFile[] files,@RequestParam("product") String JSON_prduct,HttpServletRequest request,HttpSession session) throws FileNotFoundException, IOException { //获取前台传过来的图片,和JSON字符串,这里需要转化成自己的po类到处需要在网上找JSON的几个包才能完成转化 JSONObject jsonObject = JSONObject.fromObject(JSON_prduct); //将字符串JSON数据转化成自己的po 类 Product product = (Product)JSONObject.toBean(jsonObject, Product.class); //获取配置文件中的路径 ResourceBundle resource = ResourceBundle.getBundle("application"); Map<String, Object> map = new HashMap<String, Object>(); String imageURL = null ; map.put("title","false"); // //设置需要存的图片地址 String pictureStorageAddress = resource.getString("realUploadPath")+request.getContextPath(); System.err.println("图片存放地址:"+pictureStorageAddress); //设置缩略图存放地址 String thumbanilStorageAddress = resource.getString("realThumbnailPath")+request.getContextPath(); System.err.println("缩略图存放地址:"+thumbanilStorageAddress); //循环取出图片 for (CommonsMultipartFile cmf : files) { //获取文件全名 String fileName = cmf.getOriginalFilename(); String extensionName = fileName.substring(fileName.lastIndexOf(".")+1); System.out.println("获取的扩展名:"+ extensionName); String newFileName = String.valueOf(System.currentTimeMillis())+"."+extensionName; System.out.println("新的图片名称:"+newFileName); // 存入图片后获得原图的相对地址,将相对地址存入数据库 imageURL= uploadPicturesService.uploadPictures(cmf, pictureStorageAddress, newFileName); System.err.println("原图相对地址:"+imageURL); // 获取缩略图的相对地址返回给前段使用 String thumbanilImageURL = thumbnailService.generateThumbnail(cmf, thumbanilStorageAddress, newFileName); System.err.println("缩略图相对地址:"+imageURL); } //获取原图的绝对路径 String storePictureFolder =pictureStorageAddress+request.getContextPath()+resource.getString("storePictureFolder"); System.out.println("原图的绝对路径:"+ storePictureFolder); //获取缩略图的绝对路径 String realThumbanilPath =thumbanilStorageAddress+request.getContextPath()+resource.getString("thumbnailPictureFolder"); System.out.println("缩略图的绝对路径:"+ realThumbanilPath); //读取上传图片的图片 List<String> realImageList = new ArrayList<String>(); //获取缩略图里面的所有图片 realImageList = ProductImageListImpl.printFile(realThumbanilPath); //设置返回的imageList缩略图 map.put("realImageList", realImageList); /** * 设置图片相对地址到数据库以及日期用户等 */ String userInfo = (String) session.getAttribute("userInfo"); String userInfo1 = (String) request.getSession().getAttribute("userInfo"); System.out.println("Session值1"+userInfo +"Session值2"+userInfo1); product.setProductImage(imageURL); product.setProductDeliverytime(CustomDate.getPresentTime()); // //插入到数据库 int temp = productService.inserProduct(product); if (temp > 0) { System.out.println("发布宝贝成功,已插入数据库!"); map.put("message", "恭喜发布宝贝成功!"); map.put("title", true); } return map; }
uploadPictures 上传图片的实现方法:
/** * 上传图片并返回图片的相对地址 * @throws IOException */ @Override public String uploadPictures(CommonsMultipartFile file, String realUploadPaht, String newFileName) throws IOException { ResourceBundle resource = ResourceBundle.getBundle("application"); String storePictureFolder = resource.getString("storePictureFolder"); //如果目录不存在创建目录 File uploadFile = new File(realUploadPaht+storePictureFolder); if (!uploadFile.exists()) { System.err.println(uploadFile.exists()); uploadFile.mkdirs(); } //创建输入流 InputStream inputStream = file.getInputStream(); //生成输出地址URL realUploadPaht=绝对路径,storePictureFolder=存放图片的文件夹名 +文件的名字 +file.getOriginalFilename() String outPutPath = realUploadPaht+storePictureFolder +"/"+ newFileName; //创建输出流 以及新文件名 OutputStream outputStream = new FileOutputStream(outPutPath); //设置缓冲区 byte[] buffer = new byte[1024]; //输入流读入缓冲区,输出流从缓冲区写出 while (inputStream.read(buffer)>0) { outputStream.write(buffer); } outputStream.close(); //返回原图上传的相对地址 String relative_address = storePictureFolder +"/"+ newFileName; return relative_address; }
生成缩略图的实现方法:
/** * 生成简约图的方法 * @author TangLie * */ @Service public class ThumbnailServiceImpl implements ThumbnailService{ //设置节约图的宽度以及高度 public static final int heigth = 100; public static final int width = 100; @Override public String generateThumbnail(CommonsMultipartFile file, String realUploadPaht,String newFileName) throws IOException { // TODO Auto-generated method stub ResourceBundle resource = ResourceBundle.getBundle("application"); String thumbnailPictureFolder = resource.getString("thumbnailPictureFolder"); //如果目录不存在创建目录 File uploadFile = new File(realUploadPaht+thumbnailPictureFolder); if (!uploadFile.exists()) { uploadFile.mkdirs(); } //缩略图保存的绝对地址 String des = realUploadPaht+thumbnailPictureFolder+"/"+newFileName; //按照我给的宽高生成缩略图 Thumbnails.of(file.getInputStream()).size(width, heigth).toFile(des); //返回缩略图地址 String relative_address = thumbnailPictureFolder+"/" + newFileName; return relative_address; } }
application.properties 配置:
## jdbc 驱动
jdbc.driver=com.mysql.jdbc.Driver
## jdbc url
jdbc.url=jdbc:mysql://127.0.0.1:3306/doraemon_db
## 数据库用户名以及密码
jdbc.username=root
jdbc.password=123456
## 初始化数据连接
dbcp.initialSize=10
## 运用dbcp 最大链接数据库链接数,设置为0为无限制
dbcp.maxActive=50
## 设置最大待链接中的数量,设置为0 时候,表示无限制
dbcp.maxIdle=20
#定义最小空闲
dbcp.minIdle=1
## 设置最大等待秒数,单位为毫秒,超出时间报出错误信息
dbcp.maxWait=6000
## 文件上传相关配置
## request.getContextPath() 获取当前项目明名
## 设置图片文件上传存的路径
realUploadPath = D:\softwae install\JavaItemPictureStorage/
## 设置缩略图的存放路径
realThumbnailPath= D:/softwae install/JavaItemPictureStorage/
##设置原图存放的文件夹名
storePictureFolder = /file_repository
##设置缩略图片存放文件夹名
thumbnailPictureFolder = /thumbnail_repertory
spring-mybatis.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- =================================================================================== --> <!-- 自动扫描www.kjczwl.com下面所有的类带有@controller,@service,@auto... --> <context:component-scan base-package="www.kjczwl.com.*" /> <!-- =================================================================================== --> <!-- 引入连接数据库的配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:application.properties" /> </bean> <!-- =================================================================================== --> <!--数据源配置方式,使用连接池的技术 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${dbcp.initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${dbcp.maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${dbcp.maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${dbcp.minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${dbcp.maxWait}"></property> </bean> <!-- =================================================================================== --> <!-- spring和MyBatis完美整合,故不需要mybatis的在配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描www/kjczwl/com/mapper 下面的所有xml文件 --> <property name="mapperLocations" value="classpath:www/kjczwl/com/mapper/*.xml"></property> </bean> <!-- =================================================================================== --> <!-- 自动扫描 将Mapper接口,生成代理注入到Spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="www.kjczwl.com.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- =================================================================================== --> <!-- (事务管理)通过调用连接的commit()方法来提交事务。同样,事务失败时通过调用rollback()方法进行回滚--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- =================================================================================== --> </beans>
spring-mvc.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <!-- =================================================================================== --> <!-- 使SpringMVC认为包下用了@controller注解的类是控制器 --> <context:component-scan base-package="www.kjczwl.com.controller"/> <!-- =================================================================================== --> <!-- 注解驱动,可以将请求参数绑定到控制器参数 --> <mvc:annotation-driven/> <!-- =================================================================================== --> <!-- 它会像一个检查员,对进入DispatcherServlet的URL进行筛查,如果发现是静态资源的请求,就将该请求转由Web应用服务器默认的Servlet处理,如果不是静态资源的请求,才由DispatcherServlet继续处理。 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --> <mvc:default-servlet-handler/> <!-- =================================================================================== --> <!-- 视图解析器 前缀:prefix 后缀:suffix --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- =================================================================================== --> <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> <!-- 启用是为了推迟文件解析,以便捕获文件大小异常 --> <property name="resolveLazily" value="true"/> </bean> <!-- =================================================================================== --> <!-- 启动SpringMVC的注解功能,完成请求和注解映射 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> <!-- JSON转换器 --> </list> </property> </bean> <!-- =================================================================================== --> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- =================================================================================== --> </beans>
Log4j配置:
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH:mm:ss}][%c]%m%n
maven pom依赖配置:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>www.kjczwl.com</groupId> <artifactId>Doraemon_mall</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <url>http://maven.apache.org</url> <properties> <!-- spring版本号 --> <spring.version>4.3.4.RELEASE</spring.version> <!-- mybatis版本号 --> <mybatis.version>3.2.7</mybatis.version> <!-- log4j日志文件管理包版本 --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- spring核心包end --> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- 存放所需要的依赖包 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <!-- 表示开发的时候引入,发布的时候不会加载此包 --> <scope>test</scope> </dependency> <!-- 用于生成图片的缩略图 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency> <!-- 导入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- 导入Mysql数据库链接jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL标签类 jsp页面中使用 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日志文件管理包 --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <!-- 上传组件包 end--> <!-- jackson json数据相关--> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <!-- jackson json数据相关 end--> <!-- json 依赖 start --> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.3</version> </dependency> <!-- json 依赖 end --> </dependencies> <!-- ================================================================== --> <!-- 指定maven编译方式为jdk1.8版本 --> <profiles> <profile> <id>jdk-1.8</id> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> </properties> </profile> </profiles> <!-- ================================================================== --> </project>