java上傳圖片到數據庫,涉及壓縮文件zip/rar上傳等

項目中有這個需求:javascript

1)上傳文件經過公司平臺的校驗,校驗成功後,經過接口,返回文件流;css

2)咱們根據這個文件流進行操做。這裏,先將文件流複製文件到項目臨時目錄WEB-INF/temp;文件使用完畢,刪除之;html

項目中用到了下面幾點:java

解壓zip、rar文件;jquery

臨時文件存放,使用完畢刪除之;web

對壓縮包中的圖片進行裁剪,生成預覽圖,並保存;spring

根據產品族、產品類型、產品系列展現圖片;sql

項目代碼比較多,慢慢貼出來,不足之處歡迎指正。apache

 

1.項目結構:bootstrap

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

相關文章
相關標籤/搜索