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;
}
}
阿里云上传图片
最新推荐文章于 2024-01-24 13:54:52 发布