java上传图片到数据库,涉及压缩文件zip/rar上传等
Posted 有点懒惰的大青年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java上传图片到数据库,涉及压缩文件zip/rar上传等相关的知识,希望对你有一定的参考价值。
项目中有这个需求:
1)上传文件通过公司平台的校验,校验成功后,通过接口,返回文件流;
2)我们根据这个文件流进行操作。这里,先将文件流复制文件到项目临时目录WEB-INF/temp;文件使用完毕,删除之;
项目中用到了下面几点:
解压zip、rar文件;
临时文件存放,使用完毕删除之;
对压缩包中的图片进行裁剪,生成预览图,并保存;
根据产品族、产品类型、产品系列展示图片;
项目代码比较多,慢慢贴出来,不足之处欢迎指正。
1.项目结构:
2.相关代码:
ProductController:
package com.cy.controller; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.sql.Blob; import java.sql.SQLException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ModelAndView; import com.cy.constant.Result; import com.cy.model.ImageFile; import com.cy.model.Product; import com.cy.service.ProductService; import com.cy.util.FileUtil; import com.cy.util.ImageUtil; import com.cy.vo.VoImageFile; import de.innosystec.unrar.Archive; import de.innosystec.unrar.exception.RarException; import de.innosystec.unrar.rarfile.FileHeader; import de.innosystec.unrar.rarfile.MainHeader; @Controller public class ProductController { private static Logger logger = Logger.getLogger(ProductController.class); @Autowired private ProductService productService; //增加产品页面 @RequestMapping("/toAddProduct") public ModelAndView toAddProduct(){ ModelAndView mv = new ModelAndView(); mv.setViewName("addProduct"); return mv; } //增加产品 @RequestMapping("/addProduct") @ResponseBody public String addProduct(String productFamily, String productType, String productSeries, String icon, String downloadPic ){ Product p = new Product(productFamily, productType, productSeries, icon, downloadPic); boolean result = productService.addProduct(p); if(result){ return "success"; } return "failed"; } //上传图片包页面 @RequestMapping("/toAddImageFile") public ModelAndView toAddImageFile(){ ModelAndView mv = new ModelAndView(); mv.setViewName("addImageFile"); return mv; } //根据产品族、产品类型、产品系列 展示图片 @RequestMapping("/product") public ModelAndView product(String productFamily, String productType, String productSeries){ // http://localhost:8080/MySSM/product?productFamily=传送网&productType=OWM&productSeries=MA6000 // productFamily = "接入网"; // productType = "OLT"; // productSeries = "MA5800"; try { productFamily = new String(productFamily.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ModelAndView mv = new ModelAndView(); List<VoImageFile> voImageFiles = productService.getImageFiles(productFamily, productType, productSeries); mv.setViewName("product"); mv.addObject("voImageFiles", voImageFiles); return mv; } //显示图片 @RequestMapping("/showImage") public void showImage(HttpServletRequest request, HttpServletResponse response, String packageName, String pictureName){ try { pictureName = new String(pictureName.getBytes("iso-8859-1"), "utf-8"); packageName = new String(packageName.getBytes("iso-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } Map<String, String> params = new HashMap<String, String>(); params.put("packageName", packageName); params.put("pictureName", pictureName); byte[] pic = productService.getImageByPackageNameAndPicName(params); if(pic!=null){ response.setContentType("img/jpeg"); response.setCharacterEncoding("utf-8"); try{ InputStream picture = new ByteArrayInputStream(pic); OutputStream outputStream=response.getOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = picture.read(buf,0,1024)) != -1){ outputStream.write(buf, 0, len); } outputStream.close(); }catch (IOException e) { e.printStackTrace(); } } } //上传图片zip/rar文件 @RequestMapping("/uploadImageFile") @ResponseBody public Result uploadImageFile(HttpServletRequest request, HttpServletResponse response){ Result result = new Result(); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); if(multipartResolver.isMultipart(request)){ MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request); String packageType = multiRequest.getParameter("packageType"); MultipartFile file = multiRequest.getFile("imgFile"); String packageName = file.getOriginalFilename(); //上传的包名 InputStream srcInputStream = null; //上传的源文件流 try { srcInputStream = file.getInputStream(); } catch (IOException e1) { e1.printStackTrace(); } File tempFile = FileUtil.saveTempFile(srcInputStream, packageName); //将上传的文件保存到本地 if(tempFile != null){ if(packageType.equals("single")){ //单包 String iconName = productService.getIconNameByPackage(packageName); //获取该包下面的缩略图名称 if(packageName.matches(".*\\\\.zip")){ //是zip压缩文件 try{ ZipInputStream zs = new ZipInputStream(new FileInputStream(tempFile)); BufferedInputStream bs = new BufferedInputStream(zs); ZipEntry ze; byte[] picture = null; while((ze = zs.getNextEntry()) != null){ //获取zip包中的每一个zip file entry String fileName = ze.getName(); //pictureName picture = new byte[(int) ze.getSize()]; //读一个文件大小 bs.read(picture, 0, (int) ze.getSize()); ImageFile image = new ImageFile(packageName, "N", fileName, picture); //保存image,非缩略图 productService.insertImage(image); if(fileName.equals(iconName)){ //这个picture要作为缩略图,进行裁剪、保存 String thumbName = ImageUtil.createThumbFileName(fileName); //生成缩略图名称 InputStream is = new ByteArrayInputStream(picture); byte[] thumbPic = ImageUtil.clipImage(is, 100, 100, "jpg"); //进行裁剪 ImageFile thumbImage = new ImageFile(packageName, "Y", thumbName, thumbPic); productService.insertImage(thumbImage); } } bs.close(); zs.close(); result.setStatus("success"); }catch(IOException e){ e.printStackTrace(); } }else if(packageName.matches(".*\\\\.rar")){ //是rar压缩文件 try { Archive archive = new Archive(tempFile); ByteArrayOutputStream bos = null; byte[] picture = null; FileHeader fh = archive.nextFileHeader(); while(fh!=null){ String fileName = fh.getFileNameString(); bos = new ByteArrayOutputStream(); archive.extractFile(fh, bos); picture = bos.toByteArray(); ImageFile image = new ImageFile(packageName, "N", fileName, picture); //保存image,非缩略图 productService.insertImage(image); fh = archive.nextFileHeader(); } bos.close(); archive.close(); result.setStatus("success"); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }else if(packageType.equals("multiple")){ //多包 if(packageName.matches(".*\\\\.zip")){ //多包、zip ZipFile zipFile = null; ZipInputStream zs = null; BufferedInputStream bis = null; InputStream is = null; try{ zipFile = new ZipFile(tempFile, Charset.forName("GBK")); Enumeration<? extends ZipEntry> enu = zipFile.entries(); ZipEntry ze; //遍历多包下面每一个zip while(enu.hasMoreElements()){ ze = enu.nextElement(); String zipPackageName = ze.getName(); //每个zip的包名 String iconName = productService.getIconNameByPackage(zipPackageName); //获取此zip下面的缩略图名称 zs = new ZipInputStream(zipFile.getInputStream(ze), Charset.forName("GBK")); //这个zip流 bis = new BufferedInputStream(zs); ZipEntry ze2; //zip包下面的每一个图片 while((ze2=zs.getNextEntry()) != null){ String fileName = ze2.getName(); byte[] picture = new byte[(int) ze2.getSize()]; bis.read(picture, 0, (int)ze2.getSize()); ImageFile image = new ImageFile(zipPackageName, "N", fileName, picture); //保存image,非缩略图 productService.insertImage(image); if(fileName.equals(iconName)){ //这个picture要作为缩略图,进行裁剪、保存 String thumbName = ImageUtil.createThumbFileName(fileName); //生成缩略图名称 is = new ByteArrayInputStream(picture); byte[] thumbPic = ImageUtil.clipImage(is, 100, 100, "jpg"); //进行裁剪 ImageFile thumbImage = new ImageFile(zipPackageName, "Y", thumbName, thumbPic); productService.insertImage(thumbImage); } } } result.setStatus("success"); }catch(IOException e){ e.printStackTrace(); }finally{ try{ if(is!=null) is.close(); if(bis!=null) bis.close(); if(zs!=null) zs.close(); if(zipFile!=null) zipFile.close(); }catch(IOException e){ e.printStackTrace(); } } }else if(packageName.matches(".*\\\\.rar")){ //多包、rar try{ Archive archive = new Archive(tempFile); FileHeader subFh = null; byte[] picture = null; List<FileHeader> fileHeaders = archive.getFileHeaders(); for(FileHeader fh : fileHeaders){ String rarPackageName = fh.getFileNameString(); //子包名 String iconName = productService.getIconNameByPackage(rarPackageName); //获取该包下面的缩略图名称 FileOutputStream fos = null; ByteArrayOutputStream bos = null; Archive subArchive = null; if(fh.isFileHeader()){ File subFile = new File(FileUtil.TEMP + rarPackageName); //子包的临时目录 fos = new FileOutputStream(subFile); archive.extractFile(fh, fos); //解压到临时目录 /temp/子包名 subArchive = new Archive(subFile); subFh = subArchive.nextFileHeader(); while(subFh!=null){ String picName = subFh.getFileNameString(); bos = new ByteArrayOutputStream(); subArchive.extractFile(subFh, bos); picture = bos.toByteArray(); ImageFile image = new ImageFile(rarPackageName, "N", picName, picture); //保存image,非缩略图 productService.insertImage(image); if(picName.equals(iconName)){ //这个picture要作为缩略图,进行裁剪、保存 String thumbName = ImageUtil.createThumbFileName(picName); InputStream is = new ByteArrayInputStream(picture); byte[] thumbPic = ImageUtil.clipImage(is, 100, 100, "jpg"); ImageFile thumbImage = new ImageFile(rarPackageName, "Y", thumbName, thumbPic); productService.insertImage(thumbImage); } subFh = subArchive.nextFileHeader(); } if(bos!=null) bos.close(); //注意关闭相关资源,才能成功删除临时包,文件一旦被引用则删除失败 if(fos!=null) fos.close(); if(subArchive!=null) subArchive.close(); FileUtil.deleteTempFile(subFile); //删除解压的临时子包 } } archive.close(); result.setStatus("success"); }catch(Exception e){ //catch到任何异常,返回异常 result.setStatus("exception"); e.printStackTrace(); } } } FileUtil.deleteTempFile(tempFile); //临时文件使用完毕删除 }else{ result.setStatus("failed"); } } return result; } //测试rar文件读取 @RequestMapping("/testReadRar") public void testReadRar() { try { File file = new File("E://MA6000-pic.rar"); Archive archive = new Archive(file); ByteArrayOutputStream bos = null; byte[] picture = null; FileHeader fh = archive.nextFileHeader(); while(fh!=null){ String fileName = fh.getFileNameString(); bos = new ByteArrayOutputStream(); archive.extractFile(fh, bos); picture = bos.toByteArray(); ImageFile image = new ImageFile("MA6000-pic.rar", "N", fileName, picture); //保存image,非缩略图 productService.insertImage(image); fh = archive.nextFileHeader(); } bos.close(); archive.close(); } catch (RarException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
ProductMapper:
package com.cy.dao; import java.sql.Blob; import java.util.List; import java.util.Map; import com.cy.model.ImageFile; import com.cy.model.Product; import com.cy.vo.VoImageFile; public interface ProductMapper { //增加产品 public int addProduct(Product product); //保存图片 public int insertImage(ImageFile image); //根据产品族等获取图片model public List<VoImageFile> getImageFiles(Map<String, String> params); //根据包名获取缩略图名称 public String getIconNameByPackage(String packageName); //根据包名、图片名字获取图片 public ImageFile getImageByPackageNameAndPicName(Map<String, String> params) throws Exception; }
ProductMapper.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.cy.dao.ProductMapper" > <!-- 增加产品 --> <insert id="addProduct" parameterType="com.cy.model.Product"> insert into t_product values (#{productFamily}, #{productType}, #{productSeries}, #{icon}, #{downloadPic}) </insert> <!-- 保存图片 --> <insert id="insertImage" parameterType="com.cy.model.ImageFile"> insert into t_imagefile values (#{packageName}, #{isIcon}, #{pictureName}, #{picture}) </insert> <!-- 根据产品族等获取产品model --> <select id="getImageFiles" parameterType="java.util.Map" resultType="com.cy.vo.VoImageFile"> select m.packageName, m.isIcon, m.pictureName from t_imagefile m join t_product p on m.packageName = p.downloadPic where p.productFamily = #{productFamily} and p.productType = #{productType} and p.productSeries=#{productSeries} </select> <!-- 根据包名获取缩略图名称 --> <select id="getIconNameByPackage" parameterType="java.lang.String" resultType="java.lang.String"> select icon from t_product where downloadPic = #{packageName} </select> <!-- 根据包名、图片名字获取图片 --> <select id="getImageByPackageNameAndPicName" parameterType="java.util.Map" resultType="com.cy.model.ImageFile"> select * from t_imagefile where packageName = #{packageName} and pictureName = #{pictureName} </select> </mapper>
Product实体:
package com.cy.model; public class Product { private String productFamily; private String productType; private String productSeries; private String icon; private String downloadPic; public Product(String productFamily, String productType, String productSeries, String icon, String downloadPic) { super(); this.productFamily = productFamily; this.productType = productType; this.productSeries = productSeries; this.icon = icon; this.downloadPic = downloadPic; } public Product() { super(); // TODO Auto-generated constructor stub } public String getProductFamily() { return productFamily; } public void setProductFamily(String productFamily) { this.productFamily = productFamily; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getProductSeries() { return productSeries; } public void setProductSeries(String productSeries) { this.productSeries = productSeries; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getDownloadPic() { return downloadPic; } public void setDownloadPic(String downloadPic) { this.downloadPic = downloadPic; } }
ImageFile实体:
package com.cy.model; public class ImageFile { private String packageName; private String isIcon; private String pictureName; private byte[] picture; public ImageFile(String packageName, String isIcon, String pictureName, byte[] picture) { super(); this.packageName = packageName; this.isIcon = isIcon; this.pictureName = pictureName; this.picture = picture; } public ImageFile() { super(); // TODO Auto-generated constructor stub } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getIsIcon() { return isIcon; } public void setIsIcon(String isIcon) { this.isIcon = isIcon; } public String getPictureName() { return pictureName; } public void setPictureName(String pictureName) { this.pictureName = pictureName; } public byte[] getPicture() { return picture; } public void setPicture(byte[] picture) { this.picture = picture; } }
ProductService:
package com.cy.service; import java.sql.Blob; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cy.dao.ProductMapper; import com.cy.model.ImageFile; import com.cy.model.Product; import com.cy.vo.VoImageFile; @Service public class ProductService { @Autowired private ProductMapper productMapper; //增加产品 public boolean addProduct(Product product){ boolean result = false; int count = productMapper.addProduct(product); if(count > 0){ result = true; } return result; } public int insertImage(ImageFile image) { int count = productMapper.insertImage(image); return count; } //获取 public List<VoImageFile> getImageFiles(String productFamily, String productType, String productSeries) { Map<String, String> para以上是关于java上传图片到数据库,涉及压缩文件zip/rar上传等的主要内容,如果未能解决你的问题,请参考以下文章