Java 常用工具类(9) : 图片上传至阿里云OSS

阿里云OSS工具类

加强版 : https://blog.csdn.net/Lxinccode/article/details/79698259

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.util.Date;

import com.aliyun.oss.OSSClient;

/**
 * 阿里云OSS文件上传工具类
 * @author guyinyihun
 *
 */
public class OssClientUtil {

	private static String endpoint = "xxx";
	private static String accessKeyId = "xxx";
	private static String accessKeySecret = "xxx";
	private static String bucket = "xxx";

	private static OssClientUtil ossClientUtil;

	private OssClientUtil() {
		super();
	}

	public static OssClientUtil newInstance() {
		if (ossClientUtil == null) {
			ossClientUtil = new OssClientUtil();
		}
		return ossClientUtil;
	}

	/**
	 * 文件流上传
	 * 
	 * @Title uploadPic
	 * @param @param
	 *            file
	 * @param @param
	 *            keys
	 * @param @return
	 * @return String
	 * @Explain
	 */
	public static String uploadPic(File file, String keys) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
		ossClient.putObject(bucket, keys, file);
		String url = String.valueOf(getUrl(keys));
		ossClient.shutdown();
		return url;
	}

	/**
	 * 文件流上传2
	 * 
	 * @Title uploadPic
	 * @param @param
	 *            file
	 * @param @param
	 *            keys
	 * @param @return
	 * @return String
	 * @Explain
	 */
	public static String uploadPicLongTime(File file, String keys) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
		ossClient.putObject(bucket, keys, file);
		String url = String.valueOf(getUrlLongTime(keys));
		ossClient.shutdown();
		return url;
	}

	/**
	 * 字节数组上传
	 * 
	 * @Title uploadPic
	 * @param @param
	 *            content
	 * @param @param
	 *            keys
	 * @param @return
	 * @return String
	 * @Explain
	 */
	public String uploadPic(byte[] content, String keys) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
		ossClient.putObject(bucket, keys, new ByteArrayInputStream(content));
		String url = String.valueOf(getUrl(keys));
		ossClient.shutdown();
		return url;
	}

	/**
	 * 获取文件URL
	 * 
	 * @Title getUrl
	 * @param @param
	 *            key
	 * @param @return
	 * @return URL
	 */
	public static String getUrl(String key) {
		if (key.indexOf("http") == -1) {
			OSSClient server = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
			// 设置URL过期时间为10年 3600l* 1000*24*365*10
			Date expirations = new Date(new Date().getTime() + 1000 * 60 * 5);// url超时时间
			// 生成URL
			URL url = server.generatePresignedUrl(bucket, key, expirations);
			String strUrl = String.valueOf(url);
			// 关闭client
			server.shutdown();
			return splitUrl(strUrl);
		} else {
			return splitUrl(key);
		}
	}

	/**
	 * 获取文件URL
	 * 
	 * @Title getUrl
	 * @param @param
	 *            key
	 * @param @return
	 * @return URL
	 */
	public static String getUrlOneYeay(String key) {
		if (key.indexOf("http") == -1) {
			OSSClient server = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
			// 设置URL过期时间为1年 3600l* 1000*24*365
			Date expirations = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365);// url超时时间

			// 生成URL
			URL url = server.generatePresignedUrl(bucket, key, expirations);
			String strUrl = String.valueOf(url);
			// 关闭client
			server.shutdown();
			return splitUrl(strUrl);
		} else {
			return splitUrl(key);
		}
	}

	/**
	 * 获取文件URL
	 * 
	 * @Title getUrl
	 * @param @param
	 *            key
	 * @param @return
	 * @return URL
	 */
	public static String getUrlLongTime(String key) {
		if (key.indexOf("http") == -1) {
			OSSClient server = new OSSClient(endpoint, accessKeyId, accessKeySecret);// 连接oss云存储服务器
			// 设置URL过期时间为100年 3600l* 1000*24*365*100
			Date expirations = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);// url超时时间

			// 生成URL
			URL url = server.generatePresignedUrl(bucket, key, expirations);
			String strUrl = String.valueOf(url);
			// 关闭client
			server.shutdown();
			return splitUrl(strUrl);
		} else {
			return splitUrl(key);
		}
	}

	/**
	 * 切割url
	 * 
	 * @param url
	 * @return
	 */
	public static String splitUrl(String url) {
		if (url.indexOf("?Expires") != -1) {
			return url.split("Expires")[0].substring(0,url.split("Expires")[0].length() -1 );
		}
		return url;
	}

}

自定义图片上传工具类

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;


/**
 * @Title   UploadImageUtils.java
 * @Package com.pro.huanbao.common.utils
 * @author  wanpu_ly
 * @dade    2017年11月7日 上午10:06:57
 * @version V1.0
 * 类说明:	图片上传至OSS
 */
public class UploadImageUtils {
	
	/**
	 * 返回的是阿里云的图片全路径名数组,需要可以换成网络路径
	 * @param file
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static List<String> fildUpload(MultipartFile[] file,HttpServletRequest request) throws Exception {
		// 上传图片到本地
		// 获得物理路径webapp所在路径
		String pathRoot = request.getSession().getServletContext()
				.getRealPath("");
		String path = "";
		List<String> listImagePath = new ArrayList<String>();
		for (MultipartFile mf : file) {
			if (!mf.isEmpty()) {
				// 生成uuid作为文件名称
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				// 获得文件类型(可以判断如果不是图片,禁止上传)
				String contentType = mf.getContentType();
				// 获得文件后缀名称
				String imageName = contentType.substring(contentType
						.indexOf("/") + 1);
				String allImageName = uuid + uuid +"." + imageName;
				// 文件在 /webapp/static/ 下暂存,上传至阿里云OSS后删除
				path = "/static/" + allImageName;
				mf.transferTo(new File(pathRoot + path));
				
				// 调用方法 把上传到本地的图片上传到OS
				String url = getImageUrl(request, path,uuid + allImageName);
				listImagePath.add(url);
			}
		}
		return listImagePath;
	}

	/**
	 * 上传图片到阿里云OS
	 * @Title   getImageUrl     
	 * @param   @param request
	 * @param   @param path
	 * @param   @return      
	 * @return  String 
	 * @Explain
	 */
	public static String getImageUrl(HttpServletRequest request, String path,String fileName) {
		@SuppressWarnings("deprecation")
		String realPath = request.getRealPath(path);
		String endPath = realPath.replace("\\", "\\\\");
		File file = new File(endPath);
		// 上传本地图片到OS
		
		String[] strings = DateUtil.format(new Date(), "yyyy-MM-dd").split("-");
		String imagePath = "img/"+strings[0]+"/"+strings[1]+"/"+strings[2]+"/"+fileName;
		// 图片网络路径
		String url = OssClientUtil.uploadPicLongTime(file, imagePath);
		// 删除本地图片
		file.delete();
		// 需求返回阿里云OSS文件全路径名, 需要可返回url
		return imagePath;
	}
}

springmvc 接收方法

@RequestMapping("/uploadImage")
	public String uploadImage(@RequestParam(value = "file", required = false) MultipartFile[] file,
			HttpServletRequest request) {
		try {
			List<String> imgs = UploadImageUtils.fildUpload(file, request);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}

图片上传html

<form action="/uploadImages" method="post" enctype="multipart/form-data">  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/>  
    <label></label><input type="file" name="file"/><br/> <br/> 
    <input type="submit" value="提  交"/>  
</form>


注: name 和 type 都必须为 file

依赖jar包

maven依赖: 

<!-- 阿里云OS -->
		<dependency>
			<groupId>com.aliyun.oss3</groupId>
			<artifactId>aliyun-sdk-oss3</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>com.hamcrest.core</groupId>
			<artifactId>hamcrest-core</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>com.httpcore</groupId>
			<artifactId>httpcore</artifactId>
			<version>4.4.1</version>
		</dependency>
		<dependency>
			<groupId>com.jdom</groupId>
			<artifactId>jdom</artifactId>
			<version>1.1</version>
		</dependency>
<!-- 文件上传组件 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>

jar包下载: 

http://download.csdn.net/download/lxinccode/10265847

猜你喜欢

转载自blog.csdn.net/Lxinccode/article/details/79414735