java上传图片到阿里云oss云存储中,返回url链接地址

前言:最近要做一个门户网站,图片较多,所以要采用图片服务器,我这里采用的是阿里云的oss云存储,1.个数无限制,2.阿里云备份3,性能也不错.
oss对于图片的处理,也有api,但是我这里上传的图片只需要加个水印,所以只需要在oss那边设置一个样式,那么每次上传的图片都会带水印,其余的图片的处理,没使用过,不太了解,但是oss提供在url中直接对图片进行处理,但是这种图片处理的不太好 (个人觉得).

对于要进行图片处理的朋友们,可以去看看:http://blog.csdn.net/u014559227/article/details/73467640

个人又写了一篇文章,是对图片进行压缩的,有兴趣的朋友可以相结合使用:http://blog.csdn.net/baidu_38990811/article/details/78602892

使用前pom.xml中引入:

 

		<!-- oss -->
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.7.0</version>
		</dependency>


工具类(需要的参数,自己去开通服务,自己去设置,就懂了):

 

 

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import weisheng.bizhijia.oss.ImgException;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 阿里云 OSS工具类
 * 
 * @author Monkey
 * @date 2017年9月30日下午3:38:09
 * @version 1.0
 */
@Controller
public class OSSClientUtil {

	public static final Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
	// endpoint
	private String endpoint = "";
	// accessKey
	private String accessKeyId = "";
	private String accessKeySecret = "";
	// 空间
	private String bucketName = "";
	// 文件存储目录
	private String filedir = "";

	private OSSClient ossClient;

	public OSSClientUtil() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * 初始化
	 */
	public void init() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * 销毁
	 */
	public void destory() {
		ossClient.shutdown();
	}

	/**
	 * 上传图片
	 *
	 * @param url
	 * @throws ImgException
	 */
	public void uploadImg2Oss(String url) throws ImgException {
		File fileOnServer = new File(url);
		FileInputStream fin;
		try {
			fin = new FileInputStream(fileOnServer);
			String[] split = url.split("/");
			this.uploadFile2OSS(fin, split[split.length - 1]);
		} catch (FileNotFoundException e) {
			throw new ImgException("图片上传失败");
		}
	}

	public String uploadImg2Oss(MultipartFile file) throws ImgException {
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new ImgException("上传图片大小不能超过10M!");
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2OSS(inputStream, name);
			return name;
		} catch (Exception e) {
			throw new ImgException("图片上传失败");
		}
	}

	/**
	 * 获得图片路径
	 *
	 * @param fileUrl
	 * @return
	 */
	public String getImgUrl(String fileUrl) {
		System.out.println(fileUrl);
		if (!StringUtils.isEmpty(fileUrl)) {
			String[] split = fileUrl.split("/");
			return this.getUrl(this.filedir + split[split.length - 1]);
		}
		return null;
	}

	/**
	 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
	 *
	 * @param instream
	 *            文件流
	 * @param fileName
	 *            文件名称 包括后缀名
	 * @return 出错返回"" ,唯一MD5数字签名
	 */
	public String uploadFile2OSS(InputStream instream, String fileName) {
		String ret = "";
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			// 上传文件
			PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
			ret = putResult.getETag();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType
	 *
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String getcontentType(String filenameExtension) {
		if (filenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (filenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
				|| filenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (filenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (filenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (filenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (filenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10

		Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
		// 生成URL
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}
}


SSM框架使用:

 

controller:

 

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 com.alibaba.fastjson.JSONObject;

import weisheng.bizhijia.service.UpImgService;
/**
 * 图片上传
 * @author Monkey
 * @date 2017年9月30日下午3:37:00
 * @version 1.0
 */
@Controller
public class UpImgController {
	public static final Logger logger = LoggerFactory.getLogger(UpImgController.class);
	@Autowired
	private UpImgService upImgService;
	
	@RequestMapping(value = "/headImgUpload", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String headImgUpload(HttpServletRequest request, MultipartFile file) {
		Map<String, Object> value = new HashMap<String, Object>();
		try {
			String url = upImgService.updateHead(file);
			logger.debug("图片路径{}",url);
			value.put("data", url);
			value.put("code", 0);
			value.put("msg", "图片上传成功");
		} catch (Exception e) {
			e.printStackTrace();
			value.put("code", 2000);
			value.put("msg", "图片上传成功");
		}
		return JSONObject.toJSONString(value);
	}
	
}


service:

 

 

import org.springframework.web.multipart.MultipartFile;

import weisheng.bizhijia.oss.ImgException;

public interface UpImgService {

	String updateHead(MultipartFile file)throws ImgException;
}

serviceImpl:

 

 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import weisheng.bizhijia.oss.ImgException;
import weisheng.bizhijia.oss.OSSClientUtil;
import weisheng.bizhijia.service.UpImgService;
@Service
public class UpImgServiceImpl implements UpImgService {
	public static final Logger logger = LoggerFactory.getLogger(UpImgServiceImpl.class);
	@Override
	public String updateHead(MultipartFile file) throws ImgException {
	    if (file == null || file.getSize() <= 0) {
		      throw new ImgException("file不能为空");
		    }
	        OSSClientUtil ossClient=new OSSClientUtil();
		    String name = ossClient.uploadImg2Oss(file);
		    String imgUrl = ossClient.getImgUrl(name);
		    String[] split = imgUrl.split("\\?");
		    return split[0];
	}
}

 

 

 

 

 

 

 

评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆_小茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值