1. 程式人生 > >阿里雲上傳圖片

阿里雲上傳圖片

package com.controller;

import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.WebUtils; import com.aliyun.oss.OSSClient; import com.controller.utils.AliyunOSSClientUtil; //import com.sun.image.codec.jpeg.JPEGCodec; //import com.sun.image.codec.jpeg.JPEGImageEncoder;

import io.swagger.annotations.Api;

/**

  • @class:AliyunOSSClientUtil
  • @descript:java使用阿里雲OSS儲存物件上傳圖片
  • @date:2017年3月16日 下午5:58:08
  • @author adonai */ @RestController @RequestMapping("/ossupload") @Api(“ossupload”) public class AliyunOSSClientController {

/** * 獲取圖片寬度 * * @param file * 圖片檔案 * @return 寬度 */ public static int[] getImgWidth(File file) { InputStream is = null; BufferedImage src = null; int result[] = { 0, 0 }; try { is = new FileInputStream(file); src = javax.imageio.ImageIO.read(is); result[0] = src.getWidth(null); // 得到源圖寬 result[1] = src.getHeight(null); // 得到源圖高 is.close(); } catch (Exception e) { e.printStackTrace(); } return result; }

/**
 * 採用指定寬度、高度或壓縮比例 的方式對圖片進行壓縮
 * @param imgsrc 源圖片地址
 * @param imgdist 目標圖片地址
 * @param widthdist 壓縮後圖片寬度(當rate==null時,必傳)
 * @param heightdist 壓縮後圖片高度(當rate==null時,必傳)
 * @param rate 壓縮比例 
 */
public static void reduceImg(String imgsrc, String imgdist, int widthdist,
		int heightdist, double rate) {
	try {
		File srcfile = new File(imgsrc);
		// 檢查檔案是否存在
		if (!srcfile.exists()) {
			return;
		}
		// 如果rate不為空說明是按比例壓縮
		if (rate > 0) {
			// 獲取檔案高度和寬度
			int[] results = getImgWidth(srcfile);
			if (results == null || results[0] == 0 || results[1] == 0) {
				return;
			} else {
				widthdist = (int) (results[0] * rate);
				heightdist = (int) (results[1] * rate);
			}
		}
		// 開始讀取檔案並進行壓縮
		Image src = javax.imageio.ImageIO.read(srcfile);
		BufferedImage tag = new BufferedImage((int) widthdist,
				(int) heightdist, BufferedImage.TYPE_INT_RGB);

		tag.getGraphics().drawImage(
				src.getScaledInstance(widthdist, heightdist,
						Image.SCALE_SMOOTH), 0, 0, null);

		FileOutputStream out = new FileOutputStream(imgdist);

// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); // encoder.encode(tag); out.close();

	} catch (IOException ex) {
		ex.printStackTrace();
	}
}

public String upload(String path,int type) {
	AliyunOSSClientUtil aliyunutil = new AliyunOSSClientUtil();
	File file = new File(path);
	// 初始化OSSClient
	OSSClient ossClient = aliyunutil.getOSSClient();
	String md5key = "";
	if (type==0) {
		md5key = aliyunutil.uploadObject2OSS(ossClient, file, aliyunutil.BACKET_NAME, aliyunutil.FOLDER);
	}else{
		md5key = aliyunutil.uploadObject2OSS(ossClient, file, aliyunutil.BACKET_NAME, aliyunutil.FOLDER_VI);
	}
	// logger.info("上傳後的檔案MD5數字唯一簽名:" + md5key);
	System.out.println("上傳後的檔案MD5數字唯一簽名:" + md5key);

	return md5key;
}

/**
--------------------------------------------------------------------------------
 */
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> upload(HttpServletRequest request,HttpServletResponse response) throws IOException {
	String contentType = request.getContentType();
	if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) {
		MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
				MultipartHttpServletRequest.class);
		MultipartFile myfile = multipartRequest.getFile("file");
		System.out.println("-------------------");

		Calendar calendar = Calendar.getInstance();
		String day = calendar.get(Calendar.YEAR) + File.separator + (calendar.get(Calendar.MONTH) + 1)
				+ File.separator + calendar.get(Calendar.DATE);
		String realPath = request.getSession().getServletContext()
				.getRealPath(File.separator + "upload" + File.separator + day);
		File file = new File(realPath);
		if (!file.exists()) {// 資料夾不存在 建立資料夾
			file.mkdirs();
		}
		response.setContentType("text/plain; charset=UTF-8");
		String originalFilename = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("result", "false");
		if (myfile.isEmpty()) {
			System.out.println("請選擇檔案後上傳!");
			return null;
		} else {
			originalFilename = myfile.getOriginalFilename();
			String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			if ("jpg".equalsIgnoreCase(extension) || "png".equalsIgnoreCase(extension) || "bmp".equalsIgnoreCase(extension)
					||"jpeg".equalsIgnoreCase(extension) || "gif".equalsIgnoreCase(extension)) {
				try {
					String[] name = originalFilename.split("\\.");
					String newName = name[0]+"-"+new Random().nextInt()+"."+name[1];//新增隨機數
					myfile.transferTo(new File(realPath, newName));

// int[] result = getImgWidth(new File(realPath + File.separator + newName)); // reduceImg(realPath + File.separator + newName, realPath + File.separator + newName, result[0], result[1], 0.5); upload(realPath + File.separator + newName,0);

					map.put("result", "true");
					map.put("pathUrl", "http://farmaly.oss-cn-hangzhou.aliyuncs.com/images/" + newName);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if("mp4".equalsIgnoreCase(extension)){
				try {
					myfile.transferTo(new File(realPath, originalFilename));
					upload(realPath + File.separator + originalFilename,1);
					map.put("result", "true");
					map.put("pathUrl", "http://farmaly.oss-cn-hangzhou.aliyuncs.com/video/" + originalFilename);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return map;
	}
	return null;
}

}