zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
    View Code

    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;
    }
    View Code

    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>
    View Code

    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;
        }
        
    }    
    View Code

    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;
        }
        
        
    }
    View Code

    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> params = new HashMap<String, String>();
            params.put("productFamily", productFamily);
            params.put("productType", productType);
            params.put("productSeries", productSeries);
            List<VoImageFile> imageFileList = productMapper.getImageFiles(params);
            return imageFileList;
        }
        
        //根据包名获取缩略图名称
        public String getIconNameByPackage(String packageName) {
            String iconName = productMapper.getIconNameByPackage(packageName);
            return iconName;
        }
        
        //根据包名、图片名字获取图片
        public byte[] getImageByPackageNameAndPicName(Map<String, String> params){
            byte[] pic  = null;
            try{
                ImageFile image = productMapper.getImageByPackageNameAndPicName(params);
                if(image!=null){
                    pic = image.getPicture();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
            return pic;
        }
    }
    View Code

    FileUtil.java:

    package com.cy.util;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URL;
    import java.net.URLDecoder;
    
    import org.apache.log4j.Logger;
    import org.apache.log4j.spi.LoggerFactory;
    
    import com.cy.controller.ProductController;
    
    /**
     * File工具类
     * @author CY
     *
     */
    public class FileUtil {
        
        public static final int BYTESIZE = 1024;                                        //每次读取的大小 1KB
        public static String TEMP = null;                                                //保存文件的临时目录
        
        private static Logger logger = Logger.getLogger(FileUtil.class);
        
        static
        {
            //获取保存文件的临时目录  WEB-INF/temp/
            try {
                TEMP = URLDecoder.decode(FileUtil.class.getClassLoader().getResource("../temp").getPath(), "utf-8");
                ///E:/workspace/workspace for j2ee/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/MyTest/WEB-INF/temp/
            } catch (Exception e) {
                logger.error("===============>temp directory init error.. please check===============>");
                e.printStackTrace();
            }
        }
        
    
        /**
         * 将文件流保存在项目WEB-INF/temp目录下,并且返回这个文件;
         * @param is              待转化的文件流
         * @param fileName        临时文件名
         * @return
         * @throws IOException
         */
        public static File saveTempFile(InputStream is, String fileName){
            File temp = null;
            
            if(TEMP!=null && is!=null){
                temp = new File(TEMP + fileName);
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;
                try{
                    bis = new BufferedInputStream(is);
                    bos = new BufferedOutputStream(new FileOutputStream(temp));                            //把文件流转为文件,保存在临时目录
                    int len = 0;
                    byte[] buf = new byte[10*BYTESIZE];                                                    //缓冲区
                    while((len=bis.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.flush();
                }catch(IOException e){
                    e.printStackTrace();
                }finally{
                    try {
                        if(bos!=null) bos.close();
                        if(bis!=null) bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return temp;
        }
        
        /**
         * 删除文件  用来删除临时文件
         * @param file
         */
        public static void deleteTempFile(File file){
            logger.warn("===============>begin delete temp file: =====================>" + file.getAbsolutePath());
            boolean result = file.delete();
            logger.warn("===============>delete result :===============>" + result);
        }
        
        
        
    }
    View Code

    ImageUtil.java:

    package com.cy.util;
    
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.imageio.ImageIO;
    
    public class ImageUtil {
        /**
         * 判断压缩文件的类型
         */
        
        
        /**
         * 生成缩略图名称
         * @param srcFileName
         * @return
         */
        public static String createThumbFileName(String srcFileName){
            StringBuffer thumbFileName = new StringBuffer();
            
            int pos = srcFileName.lastIndexOf(".");
            thumbFileName.append(srcFileName.substring(0, pos));
            thumbFileName.append("_small");
            thumbFileName.append(srcFileName.substring(pos, srcFileName.length()));
            return thumbFileName.toString();
        }
        
        /**
         * 对图片进行剪裁
         * @param is            图片输入流
         * @param width            裁剪图片的宽
         * @param height        裁剪图片的高
         * @param imageFormat    输出图片的格式
         * @return
         */
        public static byte[] clipImage(InputStream is,int width, int height, String imageFormat){
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                // 构造Image对象
                BufferedImage src = javax.imageio.ImageIO.read(is);
                // 缩小边长 
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                // 绘制 缩小  后的图片 
                tag.getGraphics().drawImage(src, 0, 0, width, height, null); 
                ImageIO.write(tag, imageFormat, bos);
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            return bos.toByteArray();
        }
    }
    View Code

    VoImageFile:

    package com.cy.vo;
    
    public class VoImageFile {
        private String packageName;
        private String isIcon;
        private String pictureName;
        
        
        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;
        }
        
        
    }
    View Code

    addProduct.jsp增加产品:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="resources/bootstrap/bootstrap.min.css">
    <title>增加产品</title>
    <style type="text/css">
    .container{
        margin-top: 30px;
    }
    </style>
    </head>
    <body>
    
    <div class="container">
        <form class="form-horizontal" action="addProduct" method="post">
          <div class="form-group form-group-sm">
            <label for="inputEmail3" class="col-sm-2 control-label">产品族</label>
            <div class="col-sm-10">
              <input class="form-control" placeholder="产品族" name="productFamily">
            </div>
          </div>
          <div class="form-group form-group-sm">
            <label for="inputPassword3" class="col-sm-2 control-label">款型</label>
            <div class="col-sm-10">
              <input class="form-control" placeholder="款型" name="productType">
            </div>
          </div>
          <div class="form-group form-group-sm">
            <label for="inputPassword3" class="col-sm-2 control-label">系列</label>
            <div class="col-sm-10">
              <input class="form-control" placeholder="系列" name="productSeries">
            </div>
          </div>
          <div class="form-group form-group-sm">
            <label for="inputPassword3" class="col-sm-2 control-label">缩略图名称</label>
            <div class="col-sm-10">
              <input class="form-control" placeholder="缩略图名称" name="icon">
            </div>
          </div>
          <div class="form-group form-group-sm">
            <label for="inputPassword3" class="col-sm-2 control-label">下载PIC包名</label>
            <div class="col-sm-10">
              <input class="form-control" placeholder="下载PIC包名" name="downloadPic">
            </div>
          </div>
          <div class="form-group form-group-sm">
                <div class="col-sm-offset-2 col-sm-10">
                  <button type="submit" class="btn btn-default">增加</button>
                </div>
           </div>
        </form>    
    </div>
    </body>
    <script src="resources/js/jquery.min.js"></script>
    <script src="resources/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript">
    
    </script>
    </html>
    View Code

    addImageFile.jsp增加产品图片(上传图片):

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="resources/bootstrap/bootstrap.min.css">
    <title>上传图片包文件</title>
    <style type="text/css">
    .container{
        margin-top: 30px;
    }
    </style>
    </head>
    <body>
    
    <div class="container">
        <form class="form-horizontal" action="uploadImageFile" method="post" enctype="multipart/form-data">
          <div class="form-group">
              <label class="col-sm-2 control-label">选择包类型:</label>
            <div class="col-sm-10">
                <label class="radio-inline">
                  <input type="radio" name="packageType" id="inlineRadio1" value="single"> 单包
                </label>
                <label class="radio-inline">
                  <input type="radio" name="packageType" id="inlineRadio2" value="multiple"> 多包
                </label>
            </div>
          </div>
    
          <div class="form-group">
              <label class="col-sm-2 control-label">选择文件:</label>
            <div class="col-sm-10">
                  <input type="file" id="exampleInputFile" name="imgFile">
            </div>
          </div>
    
           <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button type="submit" class="btn btn-default">上传</button>
            </div>
           </div>
        </form>
    </div>
    </body>
    <script src="resources/js/jquery.min.js"></script>
    <script src="resources/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript">
    
    </script>
    </html>
    View Code

    product.jsp展示图片:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="resources/bootstrap/bootstrap.min.css">
    <title>产品-图片展示</title>
    <style type="text/css">
    .container{
        margin-top: 30px;
    }
    .imgclass{
        
    }
    </style>
    </head>
    <body>
    
    <div class="container">
        <div class="form-horizontal">
            <c:forEach var="image" items="${voImageFiles }">
              <div class="form-group form-group-sm">
                <label for="inputEmail3" class="col-sm-2 control-label">包名</label>
                <div class="col-sm-10">
                  <input class="form-control" placeholder="Email" value="${image.packageName }">
                </div>
              </div>
              <div class="form-group form-group-sm">
                <label for="inputPassword3" class="col-sm-2 control-label">图片名</label>
                <div class="col-sm-10">
                  <input class="form-control" placeholder="Password" value="${image.pictureName }">
                </div>
              </div>
              <div class="form-group form-group-sm">
                <label for="inputPassword3" class="col-sm-2 control-label">产品图片</label>
                <div class="col-sm-10">
                    <img class="imgclass" src="showImage?packageName=${image.packageName}&pictureName=${image.pictureName}"/>
                </div>
              </div>
            </c:forEach>
            <div class="form-group form-group-sm">
                <div class="col-sm-offset-2 col-sm-10">
                  <a href="toAddProduct" class="btn btn-default">增加产品</a>
                </div>
             </div>
        </div>    
    
    </div>
    </body>
    <script src="resources/js/jquery.min.js"></script>
    <script src="resources/bootstrap/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(function(){
        
    });
    </script>
    </html>
    View Code

    Result常量:

    package com.cy.constant;
    
    /**
     * 返回的结果
     * @author CY
     *
     */
    public class Result {
        private String status;
        private Object value;
        
        public String getStatus() {
            return status;
        }
        public void setStatus(String status) {
            this.status = status;
        }
        public Object getValue() {
            return value;
        }
        public void setValue(Object value) {
            this.value = value;
        }
        
        
    }
    View Code

     单包的定义:

    多包的定义:

    展示效果:

    代码会上传到文件的。提供下载,因为一次只能上传10M的,lib包分两个上传了。都放进WEB-INF/lib下面就行。

     项目MySSM:

    链接:https://files.cnblogs.com/files/tenWood/MySSM.rar

    lib1:

    链接:https://files.cnblogs.com/files/tenWood/MySSM-lib1.rar

    lib2:

    链接:

    https://files.cnblogs.com/files/tenWood/MySSM-lib2.rar

  • 相关阅读:
    pstree---树状图的方式展现进程
    telint---切换当前正在运行的Linux系统的运行等级
    batch---系统不繁忙时执行任务
    crontab---定时任务
    runlevel---当前Linux系统的运行等级
    kill&&pkill&&killall---删除执行中的程序
    at&&atq&&atrm---定时任务
    fsck---于检查并且试图修复文件系统中的错误
    mkfs---创建Linux文件系统
    gitignore
  • 原文地址:https://www.cnblogs.com/tenWood/p/7533442.html
Copyright © 2011-2022 走看看