OSS上传图片

本文介绍了一个基于Spring MVC的图片上传控制器实现,支持多种图片格式,包括上传验证、压缩及云端存储等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后台
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>


效果图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值