Spring Boot整合阿里OSS文件储存服务器详细教程,附源码!

10 篇文章 0 订阅
1 篇文章 0 订阅

一、准备工作
开发工具idea,jdk1.8,测试工具 postman 注册阿里云服务器并创建oss储存库,
创建Spring boot空项目
二、
引入pom.xml

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>

三、
1.在配置文件中application.yml配置oss的仓库名和访问路径前缀
bucket为仓库名
preUrl为访问前缀
咱们没有配置端口所以默认端口8080
在这里插入图片描述
2.创建config.properties
endpoint为阿里云地址
accessKeyId为OSS的K
accessKeySecret为OSS的V
注意:生成K,V之后注意保存,因为这个accessKeySecret只显示一次,最好下载保存一下,以免忘记
在这里插入图片描述
四、引入我写好的Util
1.JsonResult 封装好的返回类型

package com.file.util;

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

import org.apache.commons.beanutils.BeanMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;



public class JsonResult {

	public static Map<String, Object> RetJsonPage(int code, String msg, Object data, String[] field) {

		Map<String, Object> RetMap = new HashMap<>();
		RetMap.put("code", code);
		RetMap.put("msg", msg);
		if (null == data) {
			RetMap.put("data", "");
		} else {
			RetMap.put("data", FilterMap(data, field));
			// RetMap.put("data", data);
		}

		return RetMap;

	}

	private static Map<String, Object> FilterMap(Object data, String[] field) {

		String[] arr = { "pageNum", "pageSize", "total", "list", "pages" };

		Map<String, Object> RetMap = new HashMap<>();
		Map<Object, Object> datamap = new BeanMap(data);
		if (null == field || field.length == 0) {
			field = arr;
		}

		for (int i = 0; i < arr.length; i++) {
			String key = arr[i];
			RetMap.put(key, datamap.get(key));
		}
		return RetMap;

	}

	public static Map<String, Object> RetJsone(int code, String msg, Object data) {

		Map<String, Object> RetMap = new HashMap<>();
		RetMap.put("code", code);
		RetMap.put("msg", msg);
		RetMap.put("data", data);

		return RetMap;

	}

	public static Object GetJsonVal(String str, String key) {
		Map mapTypes = JSON.parseObject(str);
		Map<String, Object> map = new HashMap<String, Object>();
		return ((JSONObject) mapTypes).getString(key);
	}

	public static List<Map<String, Object>> GetJsonList(String str) {
		List<Map<String, Object>> retmap = JSON.parseObject(str, new TypeReference<List<Map<String, Object>>>() {
		});
		return retmap;
	}

}

2.ResultCode 封装好的返回状态码

package com.file.util;

public class ResultCode {
	/** 成功 */
	public static final int SUCCESS = 200; // "成功"

	/** 没有登录 */
	public static final int NOT_LOGIN = 400; // 没有登录"),

	/** 发生异常 */
	public static final int EXCEPTION = 401; // 发生异常"),

	/** 系统错误 */
	public static final int SYS_ERROR = 402; // 系统错误"),

	/** 参数错误 */
	public static final int PARAMS_ERROR = 403; // 参数错误 "),

	/** 不支持或已经废弃 */
	public static final int NOT_SUPPORTED = 410; // 不支持或已经废弃"),

	/** AuthCode错误 */
	public static final int INVALID_AUTHCODE = 444; // 无效的AuthCode"),

	/** 太频繁的调用 */
	public static final int TOO_FREQUENT = 445; // 太频繁的调用"),

	/** 未知的错误 */
	public static final int UNKNOWN_ERROR = 499; // 未知错误");

	public static final int BALANCE_NOT_ENOUGH = 601;

	/** 操作有误 */
	public static final int WRONG_OPERATION = 602;

	/** 文件过大 */
	public static final int FILE_TOO_LARGE = 604;

	/** 结果为空 */
	public static final int RES_NULL = 700; // 结果为空 ");

	/** code没有绑定活动 */
	public static final int ACT_NULL = 701; // code没有绑定活动 ");

	/** 更新失败 */
	public static final int UPDATE_FAIL = 702; // 更新失败 ");

	/** 接口限制 */
	public static final int API_LIMIT = 703; // 更新失败 ");

	/** 失败 */
	public static final int FAIL = 704; // 失败 ");

}

3.封装好的OssUtil

package com.file.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 每个用户一个目录保存文件, 以md5为文件名保存文件避免用户上传重复文件
 * 
 * @author ChenPantao
 * @date 2017年12月15日
 */

public class OssUtil {
    
    public static String getIMGS(MultipartFile[] IMG_imgs , Long userid, String bucketName){
        String imgs = "";
        for(int i = 0 ;i<IMG_imgs.length ; i++){
            String img = uploadFile(IMG_imgs[i], userid, bucketName);
            if(i<IMG_imgs.length-1){
                imgs = imgs + img + ",";
            }else{
                imgs = imgs + img;
            }
        }
        return imgs;
    }
    
    public static synchronized String uploadFile(MultipartFile uploadFile, Long userid, String bucketName) {
        try {
            byte[] bytes = getBytes(uploadFile.getInputStream());
            String degist = getDegist(bytes);
            for(int i = degist.length() ; i < 32 ; i++){
                degist = "0" + degist;
            }
            String fileName = uploadFile.getOriginalFilename();
            Integer index = fileName.lastIndexOf(".");
            
            String fileExtension = "";
            if(index != -1){
                fileExtension = fileName.substring(fileName.lastIndexOf("."));
            }
            fileName = degist + fileExtension;
            Long fileSize = 0L + bytes.length;
            String diskName = userid + "/";
            String OSS = Oss.uploadObject2OSS(new ByteArrayInputStream(bytes), fileName, fileSize, bucketName,
                    diskName);
            if (fileName.equalsIgnoreCase(OSS + fileExtension)) {
                return diskName + fileName;
            } else {
                throw new RuntimeException("fail to upload file , ");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("fail to upload file");
        }
    }
    
    public static String getDegist(byte[] bytes) throws Exception {
        MessageDigest messagedigest = MessageDigest.getInstance("MD5");
        messagedigest.update(bytes);
        String md5 = new BigInteger(1, messagedigest.digest()).toString(16);
        return md5;
    }
    
    public static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byte[] ret = out.toByteArray();
        in.close();
        out.close();
        return ret;
    }
    
}

4.用于请求阿里云服务器的Oss

package com.file.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

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

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

public class Oss {

	private static final Logger LOG = LoggerFactory.getLogger(Oss.class);

	private static String ENDPOINT;

	private static String ACCESS_KEY_ID;

	private static String ACCESS_KEY_SECRET;

	// init static datas
	static {
		ResourceBundle bundle = PropertyResourceBundle.getBundle("config");
		ENDPOINT = bundle.containsKey("endpoint") == false ? "" : bundle.getString("endpoint");
		ACCESS_KEY_ID = bundle.containsKey("accessKeyId") == false ? "" : bundle.getString("accessKeyId");
		ACCESS_KEY_SECRET = bundle.containsKey("accessKeySecret") == false ? "" : bundle.getString("accessKeySecret");
	}

	private static final OSSClient getOSSClient() {
		return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	}

	public static final boolean createBucket(String bucketName) {
		Bucket bucket = getOSSClient().createBucket(bucketName);
		return bucketName.equals(bucket.getName());
	}

	public static final void deleteBucket(String bucketName) {
		getOSSClient().deleteBucket(bucketName);
		LOG.info("删除" + bucketName + "Bucket成功");
	}

	public static final String uploadObject2OSS(File file, String bucketName, String diskName) {
		String resultStr = null;
		try {
			InputStream is = new FileInputStream(file);
			String fileName = file.getName();
			Long fileSize = file.length();
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));

			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
			// 上传文件
			PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName, is, metadata);
			// 解析结果
			resultStr = putResult.getETag();
		} catch (Exception e) {
			LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
		}
		return resultStr;
	}

	public static final String uploadObject2OSS2(MultipartFile file, String bucketName, String diskName,
			String fileName) {
		String resultStr = null;
		try {
			InputStream is = file.getInputStream();
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			// 上传文件
			PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName, is, metadata);
			// 解析结果
			resultStr = putResult.getETag();
		} catch (Exception e) {
			LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
		}
		return resultStr;
	}

	public static final String uploadString2OSS(String str, String fileName, String bucketName, String diskName) {
		String resultStr = null;
		try {
			byte[] content = str.getBytes();
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(content.length);
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + content.length + "Byte.");
			// 上传文件
			PutObjectResult putResult = getOSSClient().putObject(bucketName, diskName + fileName,
					new ByteArrayInputStream(content), metadata);
			// 解析结果
			resultStr = putResult.getETag();
		} catch (Exception e) {
			LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
		}
		return resultStr;
	}

	public static final String uploadObject2OSS(InputStream is, String fileName, Long fileSize, String bucketName,
			String diskName) {

		// 获取ossClient
		OSSClient ossClient = getOSSClient();

		try {

			// 生成OSS中Object的元数据
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(is.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			metadata.setContentType(getContentType(fileName));
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

			// 上传文件
			PutObjectResult putResult = ossClient.putObject(bucketName, diskName + fileName, is, metadata);

			// 解析结果
			return putResult.getETag();

		} catch (Exception e) {

			LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
			throw new RuntimeException("上传文件失败");

		} finally {
			ossClient.shutdown();
		}
	}

	public static final InputStream getOSS2InputStream(String bucketName, String diskName, String key) {
		OSSObject ossObj = getOSSClient().getObject(bucketName, diskName + key);
		return ossObj.getObjectContent();
	}

	public static void deleteFile(String bucketName, String diskName, String key) {
		getOSSClient().deleteObject(bucketName, diskName + key);
		LOG.info("删除" + bucketName + "下的文件" + diskName + key + "成功");
	}

	public static final String getContentType(String fileName) {
		String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);

		if ("bmp".equalsIgnoreCase(fileExtension))
			return "image/bmp";
		if ("gif".equalsIgnoreCase(fileExtension))
			return "image/gif";
		if ("jpeg".equalsIgnoreCase(fileExtension) || "jpg".equalsIgnoreCase(fileExtension)
				|| "png".equalsIgnoreCase(fileExtension))
			return "image/jpeg";
		if ("html".equalsIgnoreCase(fileExtension))
			return "text/html";
		if ("txt".equalsIgnoreCase(fileExtension))
			return "text/plain";
		if ("vsd".equalsIgnoreCase(fileExtension))
			return "application/vnd.visio";
		if ("ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension))
			return "application/vnd.ms-powerpoint";
		if ("doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension))
			return "application/msword";
		if ("xml".equalsIgnoreCase(fileExtension))
			return "text/xml";
		return "text/html";
	}
}

五、FileController 上传接口

package com.file.controller;

import com.file.util.JsonResult;
import com.file.util.OssUtil;
import com.file.util.ResultCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

//	@Autowired
//	private OSSConfig oSSConfig;

	@Value("${oss.bucket}")
	private String bucket;

	@Value("${oss.preUrl}")
	private String preUrl;

	//@ApiOperation(value = "上传单个文件")
	@PostMapping("/singleFile")
	public Map<String, Object> uploadFile(@RequestParam MultipartFile IMG_gicon) {
		String gicon = OssUtil.uploadFile(IMG_gicon, 55555L,bucket);
		String url = preUrl+gicon;
		return JsonResult.RetJsone(ResultCode.SUCCESS, "上传成功", url);
	}

	// @ApiOperation(value = "上传多个文件")
	@PostMapping("/multipartFiles")
	public Map<String, Object> uploadFiles(
			 @RequestParam MultipartFile[] IMG_gicons) {
		String gimg = OssUtil.getIMGS(IMG_gicons, 55555L, bucket);
		return JsonResult.RetJsone(ResultCode.SUCCESS, "多文件上传成功", gimg);
	}
	

}

六、测试
在这里插入图片描述
到这里就整合完成了,喜欢的可以点个赞哦
在这里插入图片描述
关注微信公众号领取项目源码哦!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值