1. 程式人生 > >OSS上傳圖片

OSS上傳圖片

後臺
package com.xiaohe.qd.controller;

import java.io.File;
import java.io.InputStream;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
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.MultipartRequest;

import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.ServiceException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSErrorCode;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.CannedAccessControlList;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.xiaohe.qd.util.Constants;
import com.xiaohe.qd.util.ImageUtil;
import com.xiaohe.qd.util.Property;

@Controller
@RequestMapping("/upload")
@Scope("prototype")
public class UploadController extends BaseController {

	public final static String savePath = Constants.DIR_TEMP;
	public final static Double width = 800.0;
	public final static Double height = 800.0;
	public final static Boolean largePic = false;
	public final static String[] types = new String[] { ".bmp", ".png", ".gif", ".jpeg", ".pjpeg", ".jpg" };
	public final static String[] fileType = new String[] { ".exe", ".jar", ".dll", ".jsp", ".class", ".sh", ".bat" };
	public final static long maxSize = 10000000;
	public final static long maxFileSize = 20000000;

	@RequestMapping(value = "/img.html", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String img(HttpServletRequest request, HttpServletResponse response) {
		MultipartRequest multipartRequest = (MultipartRequest) request;
		MultipartFile imgFile = multipartRequest.getFile("imgFile");
		String imgFileFileName = imgFile.getOriginalFilename();
		try {
			long size = imgFile.getSize();
			if (size > maxSize) {
				alert(response, 1, "圖片應小於10M!");
				return null;
			}
			boolean admit = true;
			String fileType = ".jpg";
			for (int i = 0; i < types.length; i++) {
				if (types[i].equalsIgnoreCase(imgFileFileName.substring(imgFileFileName.lastIndexOf(".")))) {
					admit = false;
					if (types[i].endsWith(".gif"))
						fileType = ".gif";
					if (types[i].endsWith(".png"))
						fileType = ".png";
				}
			}
			if (admit) {
				alert(response, 1, "上傳圖片型別不正確!");
				return null;
			}
			String fileName = (System.currentTimeMillis() + (new Random(999999).nextLong())) + fileType;
			try {
				if (null == imgFile || size < 0) // 檔案不存在時
					return null;
				String bucketName = "hhr360oss";
				// 使用預設的OSS伺服器地址建立OSSClient物件。
				OSSClient client = new OSSClient(Property.getProperty("OSS_ACCESS_ID"), Property.getProperty("OSS_ACCESS_KEY"));
				ensureBucket(client, bucketName);
				ObjectMetadata objectMeta = new ObjectMetadata();
				objectMeta.setContentLength(imgFile.getSize());
				InputStream is = imgFile.getInputStream();
				client.putObject(bucketName, fileName, is, objectMeta);
				String saveUrl = Property.getProperty("OSS_URL") + fileName;
				JSONObject obj = new JSONObject();
				obj.put("fileName", imgFileFileName);
				obj.put("fileSize", (int) size / 1024);
				obj.put("error", 0);
				obj.put("url", saveUrl);
				obj.put("saveDir", saveUrl);
				writeJson(response, obj);
				return null;
			} catch (Exception e) {
				e.printStackTrace();
				alert(response, 1, "上傳圖片異常!");
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {

		try {
			// 建立bucket
			client.createBucket(bucketName);
			client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
		} catch (ServiceException e) {
			if (!OSSErrorCode.BUCKES_ALREADY_EXISTS.equals(e.getErrorCode())) {
				// 如果Bucket已經存在,則忽略
				throw e;
			}
		}
	}

	/**
	 * 圖片壓縮
	 * 
	 * @param picFrom
	 *            待壓縮的圖片儲存路徑
	 * @param picTo
	 *            壓縮後的圖片儲存路徑
	 * @param width
	 *            寬度
	 * @param height
	 *            高度
	 * @throws Exception
	 */
	public static void comPress(String picFrom, String picTo, double width, double height) throws Exception {
		ImageUtil.resize(picFrom, picTo, (int) width, (int) height);
	}

	/**
	 * 圖片壓縮 作者:漆傳濤
	 * 
	 * @param savePath
	 *            檔案儲存的真實路徑
	 * @param oldFile
	 *            壓縮檔案
	 * @param width
	 *            檔案壓縮寬
	 * @param height
	 *            檔案壓縮高
	 * @throws Exception
	 */
	public void comPress(String savePath, File oldFile, double width, double height, boolean largePic) {
		try {
			if (!oldFile.exists()) // 檔案不存在時
				return;
			String picFrom = oldFile.getAbsolutePath();
			int quality = (int) ((largePic ? 200000d : 80000d) / oldFile.length() * 100);
			if (quality >= 100) {
				quality = 0;
			} else {
				if (quality < 70) {
					quality = 50;
				}
			}
			ImageUtil.resize(picFrom, savePath, (int) width, (int) height, quality);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void alert(HttpServletResponse response, int error, String msg) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			JSONObject array = new JSONObject();
			array.put("error", error);
			array.put("message", msg);
			response.getWriter().write(array.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
}
package com.xiaohe.qd.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.im4java.core.ConvertCmd;
import org.im4java.core.IMOperation;

/**
 * 
 * @author 
 * 
 */
public class ImageUtil {

	private static Log log = LogFactory.getLog(ImageUtil.class);
	public static String imageMagickPath = null;

	static {
		imageMagickPath = "C:\\Program Files (x86)\\ImageMagick-6.7.9-Q8";
	}

	public final static int PHOTO_RATIO = 800; // 縮放圖片係數

	/**
	 * 剪下圖片
	 * 
	 * @param x
	 *            座標x
	 * @param y
	 *            座標y
	 * @param width
	 *            寬度
	 * @param height
	 *            高度
	 * @param oldPath
	 *            相對路徑
	 * @return 返回新的儲存路徑
	 * @throws Exception
	 *             描述: 按照座標要求裁剪圖片。
	 */
	public final static String cutImage(HttpServletRequest request, int x, int y, int width, int height,
			String oldPath) throws Exception {
		if (oldPath == null)
			return null;
		String newPath = oldPath.replace(Constants.DIR_TEMP, Constants.DIR_PIC);
		String realPath = request.getServletContext().getRealPath(oldPath);
		String newRealPath = request.getServletContext().getRealPath(newPath);
		IMOperation op = new IMOperation();
		op.addImage(realPath);
		op.crop(width, height, x, y);
		op.addImage(newRealPath);
		runOp(op);
		return newPath;
	}

	/**
	 * 計算字的長度
	 * 
	 * @param text
	 * @return
	 */
	public static int getLength(String text) {
		int length = 0;
		for (int i = 0; i < text.length(); i++) {
			if ((text.charAt(i) + "").getBytes().length > 1) {
				length += 2;
			} else {
				length += 1;
			}
		}
		return length / 2;
	}

	/**
	 * 圖片壓縮
	 * 
	 * @param picFrom
	 * @param picTo
	 * @param widthdist
	 * @param heightdist
	 */
	public static void resize(String picFrom, String picTo, int widthdist,
			int heightdist) {
		resize(picFrom, picTo, widthdist, heightdist, 0);
	}

	/**
	 * 圖片壓縮
	 * 
	 * @param picFrom
	 * @param picTo
	 * @param widthdist
	 * @param heightdist
	 */
	public static void resize(String picFrom, String picTo, int widthdist,
			int heightdist, int quality) {
		try {
			BufferedImage bi = ImageIO.read(new File(picFrom));
			int new_w = bi.getWidth();
			int new_h = bi.getHeight();
			double rate = 1;
			if (new_w > widthdist) {
				rate = new_w / widthdist;
				new_h = (int)(new_h / rate);
				new_w = widthdist;
			}
			if (new_h > heightdist) {
				rate = new_h / heightdist;
				new_h = heightdist;
				new_w = (int)(new_w / rate);
			}
			resizeImage(picFrom, picTo, new_w, new_h, quality);
		} catch (RuntimeException e) {
			log.error(e.getMessage());
		} catch (Exception ex) {
			log.error(ex.getMessage());
		} catch (Throwable e) {
			log.error(e.getMessage());
		}
	}

	public static JSONObject getImgData(String picFrom) {
		return getImgWidthHeight(picFrom);
	}

	public static void resize(String picFrom, String picTo, int ratio)
			throws Exception {
		BufferedImage bi = ImageIO.read(new File(picFrom));
		// 原始圖片屬性
		int srcWidth = bi.getWidth();
		int srcHeight = bi.getHeight();
		// 生成圖片屬性
		int newWidth = srcWidth;
		int newHeight = srcHeight;
		// 如果超出最大寬或高就壓縮
		if (srcWidth > ratio || newHeight > ratio) {
			// 生成圖片width, height計算
			if (srcWidth >= srcHeight) {
				if (srcWidth < ratio) {
					return;
				}
				newWidth = ratio;
				newHeight = (ratio * srcHeight / srcWidth);
			} else {
				if (srcHeight < ratio) {
					return;
				}
				newHeight = ratio;
				newWidth = (ratio * srcWidth / srcHeight);
			}
		}
		resize(picFrom, picTo, newWidth, newHeight);
	}

	/**
	 * 方法描述: 驗證檔案型別
	 * 
	 * @param filename
	 * @return
	 */
	public static boolean validateImage(String filename) {
		// 定義可上傳檔案的 型別
		List<String> fileTypes = new ArrayList<String>();

		// 圖片
		fileTypes.add("jpg");
		fileTypes.add("jpeg");
		fileTypes.add("bmp");
		fileTypes.add("gif");
		fileTypes.add("png");

		// 得到檔案尾數 並 進行小寫轉換
		String postfix = filename.substring(filename.lastIndexOf(".") + 1)
				.toLowerCase();
		return fileTypes.contains(postfix) ? true : false;
	}

	public static void resize(String picFrom, String picTo) throws Exception {
		resize(picFrom, picTo, PHOTO_RATIO);
	}

	public static void main(String[] args) throws Exception {
		// resizeImg("G:/xiaoguo/46留言反饋/此方.jpg", "G:/xiaoguo/46留言反饋/此方2.jpg",
		// 200, 200);
		resize("G:/xiaoguo/46留言反饋/此方.jpg", "G:/xiaoguo/46留言反饋/此方2.jpg", 200,
				200);
		// String img = "/temp/yancheng.jpg";
		// String imgtemp = img.substring(img.lastIndexOf("/")+1,
		// img.lastIndexOf("."));
		// System.out.println(imgtemp);
	}

	public static JSONObject getImgWidthHeight(String picFrom) {
		try {
			JSONObject obj = new JSONObject();
			BufferedImage bi = ImageIO.read(new File(picFrom));
			// 原始圖片屬性
			int srcWidth = bi.getWidth();
			int srcHeight = bi.getHeight();
			obj.put("width", srcWidth);
			obj.put("height", srcHeight);
			return obj;
		} catch (RuntimeException e) {
			log.error(e.getMessage());
		} catch (Exception ex) {
			log.error(ex.getMessage());
		} catch (Throwable e) {
			log.error(e.getMessage());
		}
		return null;
	}

	/**
	 * 根據尺寸縮放圖片
	 * 
	 * @param width
	 *            縮放後的圖片寬度
	 * @param height
	 *            縮放後的圖片高度
	 * @param srcPath
	 *            源圖片路徑
	 * @param newPath
	 *            縮放後圖片的路徑
	 */
	public static void resizeImage(String srcPath, String newPath, int ratio)
			throws Exception {
		BufferedImage bi = ImageIO.read(new File(srcPath));
		// 原始圖片屬性
		int srcWidth = bi.getWidth();
		int srcHeight = bi.getHeight();
		// 生成圖片屬性
		int newWidth = srcWidth;
		int newHeight = srcHeight;
		// 如果超出最大寬或高就壓縮
		if (srcWidth > ratio || newHeight > ratio) {
			// 生成圖片width, height計算
			if (srcWidth >= srcHeight) {
				if (srcWidth < ratio) {
					return;
				}
				newWidth = ratio;
				newHeight = (ratio * srcHeight / srcWidth);
			} else {
				if (srcHeight < ratio) {
					return;
				}
				newHeight = ratio;
				newWidth = (ratio * srcWidth / srcHeight);
			}
		}
		resizeImage(srcPath, newPath, newWidth, newHeight,0);
	}

	/**
	 * 根據尺寸縮放圖片
	 * 
	 * @param width
	 *            縮放後的圖片寬度
	 * @param height
	 *            縮放後的圖片高度
	 * @param srcPath
	 *            源圖片路徑
	 * @param newPath
	 *            縮放後圖片的路徑
	 */
	public static void resizeImage(String srcPath, String newPath, int width,
			int height,int quality) throws Exception {
		IMOperation op = new IMOperation();
		op.addImage(srcPath);
		op.resize(width, height);
		if(quality>0&&quality<100){
			op.quality(quality*1d);
		}
		op.addImage(newPath);
		runOp(op);
	}
	
	public static void resizeImage(String srcPath, String newPath, int width,
			int height) throws Exception {
		resize(srcPath, newPath, width, height, 0);
	}
	
	public static void runOp(IMOperation op) throws Exception {
		ConvertCmd convert = new ConvertCmd();
//		convert.setSearchPath(imageMagickPath);
		convert.run(op);
	}
}

html

	<!-- 上傳頭像彈窗 -->
	<div  class="txFc">
		<div id="uploader-demo">
			<a class="uploader-clos">X</a>
		    <!--用來存放item-->
		    <div id="fileList" class="uploader-list"></div>
		    <input type="file" name="imgFile" id="filePicker" value="選擇圖片"/>
		    <div class="uploader-tip">格式:gif,jpg,jpeg,bmp,png </div>
		    <input type="hidden" name="userAvatar" id="userAvatar" value=""/>
		</div>
	</div>

js
<link href="${ctx}/js/uploadify-v2.1.4/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="${ctx}/js/uploadify-v2.1.4/swfobject.js"></script>
<script	type="text/javascript" src="${ctx}/js/uploadify-v2.1.4/jquery.uploadify.v2.1.4.min.js"></script>
<script type="text/javascript">
jQuery("#filePicker").uploadify({
	'uploader' : '${ctx}/js/uploadify-v2.1.4/uploadify.swf?random=' + (new Date()).getTime(),
	'script' : '${ctx}/upload/img.html',//請求地址
	'cancelImg' : '${ctx}/js/uploadify-v2.1.4/cancel.png',
	'fileDataName' : 'imgFile', //相當於  file 控制元件的 name
	'auto' : true,
	'multi' : false,
	'buttonImg' : '${ctx}/images/fileBtn.png',
	'height' : '31',
	'width' : '86',
	'fileDesc' : '能上傳的圖片型別:jpg,gif,bmp,jpeg,png', //出現在上傳對話方塊中的檔案型別描述
	'fileExt' : '*.jpg;*.gif;*.bmp;*.jpeg;*.png', //控制可上傳檔案的副檔名,啟用本項時需同時宣告fileDesc
	'sizeLimit' : 3*1024*1024,
	onComplete:function(event,queueID,fileObj,response,data){
			var jsondata = eval("("+response+")");
			if(jsondata.error==1){
				Dialog.alert(jsondata.message);
				return false;
			}
			$(".txFc").hide();
			$(".user-tx img").attr("src", jsondata.saveDir);
			$("#userAvatar").val(jsondata.saveDir);//圖片的地址
			$("#span1").html("已上傳檔案:"+jsondata.fileName);
			$.post("${ctx}/ai/editUserAvatar.html",{userAvatar:$("#userAvatar").val()},function(data){
				if (data.success == 1) {
					globalTip("上傳圖片成功!");
				}
			}, "json");
		},
		'onSelect' : function(event,queueID, fileObj) {
			if (fileObj.size > 5*1024*1024) {
				Dialog.alert("圖片"+ fileObj.name+ " 應小於5M");
				jQuery("#filePicker").uploadifyClearQueue();
			}
		}
});
</script>


效果圖