spring 對上傳圖片處理

安_子發表於2016-11-17
package com.maizuo.web.controller;  

import com.maizuo.domain.Result;  
import com.maizuo.util.ConstantsConfig;  
import com.maizuo.util.Upload;  
import hyxlog.Log;  
import net.sf.json.JSONObject;  
import org.apache.commons.lang.StringUtils;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.*;  
import org.springframework.web.multipart.MultipartFile;  
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServletRequest;  
import java.awt.image.BufferedImage;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.Date;  
import java.util.List;  

/** 
 * Created by qiyang on 2015/6/15 and improved by heisenberg on 2016/04/18 
 */  
@Controller  
@RequestMapping("/api/upload")  
public class UploadController {  
    @RequestMapping(value = "/img", method = RequestMethod.POST)  
    @ResponseBody  
    public Result uploadImg(@RequestParam(value = "file", required = false) MultipartFile file, String pathName,  
            Integer sizeRule, Integer isDeviation, HttpServletRequest request)  
                    throws FileNotFoundException, IOException {  
        String loghead = "通用介面-上傳圖片:";  

        JSONObject json = new JSONObject();  
        if (file == null) {  
            Log.info(loghead + "上傳失敗:檔案為空");  
            return new Result(900001, "", "上傳失敗:檔案為空");  
        }  
        if (StringUtils.isBlank(pathName)) {  
            pathName = ConstantsConfig.getString("DEFALTUPLOADPATH");  
        }  
        List<Object> uploadPathNames = ConstantsConfig.getList("UPLOADPATHNAMES");  
        boolean flag = false;  
        for (int i = 0; i < uploadPathNames.size(); i++) {  
            if (pathName.equals(uploadPathNames.get(i))) {  
                flag = true;  
            }  
        }  
        if (!flag) {  
            Log.info(loghead + "上傳失敗:上傳路徑無效");  
            return new Result(900001, "", "上傳失敗:上傳路徑無效");  
        }  
        String fileName = file.getOriginalFilename();  
        // 獲取上傳副檔名  
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());  
        // 對副檔名進行小寫轉換  
        fileExt = fileExt.toLowerCase();  
        // 圖片檔案大小過濾  
        if (!"jpg".equals(fileExt) && !"jpeg".equals(fileExt) && !"png".equals(fileExt) && !"bmp".equals(fileExt)  
                && !"gif".equals(fileExt)) {  
            Log.info(loghead + "上傳失敗:無效圖片檔案型別");  
            return new Result(900001, "", "上傳失敗:無效圖片檔案型別");  
        }  
        long fileSize = file.getSize();  
        Log.info(loghead + "fileInfo:fileName=" + fileName + "&fileSize=" + fileSize);  
        if (fileSize <= 0) {  
            Log.info(loghead + "上傳失敗:檔案為空");  
            return new Result(900001, "", "上傳失敗:檔案為空");  
        } else if (fileSize > (500 * 1024)) {  
            Log.info(loghead + "上傳失敗:檔案大小不能超過500K");  
            return new Result(900001, "", "上傳失敗:檔案大小不能超過500K");  
        }  
        File tmpFile = null;  
        // 判斷檔案是否為空  
        if (!file.isEmpty()) {  
            String uploadPath = request.getSession().getServletContext().getRealPath("/") + "/upload/";  
            File uploadDir = new File(uploadPath);  
            if (uploadDir.exists() && uploadDir.isDirectory()) {  
                String[] childFileNameList = uploadDir.list();  
                if (childFileNameList != null) {  
                    File temp;  
                    for (int i = 0; i < childFileNameList.length; i++) {  
                        temp = new File(uploadPath + childFileNameList[i]);  
                        if (temp.isFile()) {  
                            temp.delete();  
                        }  
                    }  
                }  
            } else {  
                uploadDir.mkdir();  
            }  

            try {  
                Date now = new Date();  
                String tmpFileName = String.valueOf(now.getTime()) + Math.round(Math.random() * 1000) + "." + fileExt;  
                // 檔案儲存路徑  
                String tmpFilePath = uploadPath + tmpFileName;  
                tmpFile = new File(tmpFilePath);  
                file.transferTo(tmpFile);  
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(tmpFile));  
                int imgWidth = sourceImg.getWidth();  
                int imgHeight = sourceImg.getHeight();  
                System.out.println("上傳的圖片寬:" + imgWidth);  
                System.out.println("上傳的圖片高:" + imgHeight);  
                // 圖片檔案尺寸過濾  
                if (sizeRule == null) {  
                    // 上傳到圖片伺服器  
                    String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");  
                    json.put("fileName", fileName);  
                    json.put("url", imgUrl);  
                    json.put("imgWidth", imgWidth);  
                    json.put("imgHeight", imgHeight);  
                    return new Result(0, json, "success");  
                } else {  
                    System.out.println("前端選擇圖片尺寸規則" + sizeRule);  
                    int ruleWidth = 0;  
                    int ruleHeight = 0;  
                    try {  
                        String imgSizeRule = ConstantsConfig.getString("UPLOADIMG_RULE" + sizeRule);  
                        String imgSizeRule_width_height[] = imgSizeRule.split(",");  
                        String imgSizeRule_width = imgSizeRule_width_height[0];  
                        String imgSizeRule_height = imgSizeRule_width_height[1];  
                        ruleWidth = Integer.parseInt(imgSizeRule_width);  
                        ruleHeight = Integer.parseInt(imgSizeRule_height);  
                    } catch (Exception e) {  
                        System.out.println("沒有配置尺寸規則" + sizeRule);  
                        json.put("fileName", fileName);  
                        json.put("imgWidth", imgWidth);  
                        json.put("imgHeight", imgHeight);  
                        return new Result(-1, json, "配置系統沒有配置上傳圖片尺寸規則" + sizeRule  
                                + ",請前端修改引數sizeRule值或管理員在配置系統配置sizeRule" + sizeRule + "規則對應的配置項");  
                    }  
                    if (isDeviation == null) {  
                        System.out.println("嚴格限制圖片尺寸");  
                        if (ruleWidth == imgWidth && ruleHeight == imgHeight) {  
                            String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");  
                            json.put("fileName", fileName);  
                            json.put("url", imgUrl);  
                            json.put("imgWidth", imgWidth);  
                            json.put("imgHeight", imgHeight);  
                            return new Result(0, json, "success");  
                        } else {  
                            json.put("fileName", fileName);  
                            json.put("imgWidth", imgWidth);  
                            json.put("imgHeight", imgHeight);  
                            json.put("ruleWidth", ruleWidth);  
                            json.put("ruleHeight", ruleHeight);  
                            return new Result(-1, json, "請上傳" + ruleWidth + "*" + ruleHeight + "px的圖片");  
                        }  
                    } else {  
                        int deviation = Integer.parseInt(ConstantsConfig.getString("UPLOADIMG_DEVIATION"));  
                        System.out.println("允許尺寸誤差在" + deviation + "以內");  
                        if (Math.abs(ruleWidth - imgWidth) <= deviation  
                                && Math.abs(ruleHeight - imgHeight) <= deviation) {  
                            String imgUrl = Upload.upload(tmpFile, "/" + pathName + "/");  
                            json.put("fileName", fileName);  
                            json.put("url", imgUrl);  
                            json.put("imgWidth", imgWidth);  
                            json.put("imgHeight", imgHeight);  
                            return new Result(0, json, "success");  
                        } else {  
                            json.put("fileName", fileName);  
                            json.put("imgWidth", imgWidth);  
                            json.put("imgHeight", imgHeight);  
                            json.put("ruleWidth", ruleWidth);  
                            json.put("ruleHeight", ruleHeight);  
                            return new Result(-1, json, "請上傳" + ruleWidth + "*" + ruleHeight + "px的圖片");  
                        }  
                    }  
                }  
            } catch (Exception e) {  
                e.printStackTrace();  
                Log.info(loghead + "上傳失敗:檔案上傳失敗");  
                return new Result(900001, "", "上傳失敗:檔案上傳異常");  
            } finally {  
                // 刪除臨時檔案  
                if (tmpFile.exists()) {  
                    tmpFile.deleteOnExit();  
                    Log.info(loghead + "刪除臨時檔案" + tmpFile.getAbsolutePath());  
                }  
            }  
        }  
        return new Result(-1, json, "後臺校驗上傳圖片流程異常");  
    }  
}  

相關文章