java 上传文件至阿里云oss服务器

阿里云SDK示例上传文件
阿里云oss服务github地址

导入jar包

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

配置文件

aliyun:
  oss: 
    endpoint: https://oss-cn-hangzhou.aliyuncs.com
    accessKeyId: XXXX
    accessKeySecret: XXXXXXXX

bean注入

@Configuration
public class AliyunConfiguration {

	@Value("${aliyun.oss.endpoint}")
	private String endpoint;
	
	@Value("${aliyun.oss.accessKeyId}")
	private String accessKeyId;
	
	@Value("${aliyun.oss.accessKeySecret}")
	private String accessKeySecret;
	
	@Bean
    public OSS ossClient(){
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
}

底层上传文件流

private final static String accessUrl = "https://"+Constant.BUCKET_NAME+".oss-cn-hangzhou.aliyuncs.com/";

/**
 * 底层上传文件至阿里云服务器
 * @param inputStream 传输的文件流
 * @param fileName 自定义文件名(含文件夹)
 * @return 上传后的文件路径
 * @throws Exception
 */
private String uploadFileStream(InputStream inputStream,String fileName) throws Exception {
	
	String fileUrl = String.valueOf("");
	try {
		ossClient.putObject(Constant.BUCKET_NAME, fileName, inputStream);
		fileUrl = accessUrl+fileName;
	}catch (Exception e) {
		throw new Exception("上传文件异常");
	}
	return fileUrl;
}

上传文件,文件名为当前时间时间戳

@Service
public class AliyunService {

	private final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
	private final static DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("yyyyMM");
	
	@Autowired
	private OSS ossClient;
	
	/** 上传文件  **/
	public String uploadFile(MultipartFile file,String clinicID) throws Exception {
		
		String fileUrl = String.valueOf("");
		String originName = file.getOriginalFilename();
		String endName = null;//提取文件名后缀,仅处理简单后缀名
		if (originName.lastIndexOf(".") >= 0) {
			endName = originName.substring(originName.lastIndexOf("."));
		}
		//文件名
		String newName = formatter.format(LocalDateTime.now())+endName;	
		//文件夹
		String folderName = ymFormatter.format(LocalDateTime.now())+"/";	
		
		try {
			//含文件夹名的文件名
			String fileName = folderName+newName;
			InputStream inputStream = file.getInputStream();
			fileUrl = this.uploadFileStream(inputStream, fileName);
		} catch (IOException e) {
			throw new IOException("文件流异常");
		}
		return fileUrl;
	}
}

上传base64图片(限制图片大小为10M)

byte[] bytes = MathUtil.imageBase64ToByteArray(url, 10485760L);
InputStream inputStream = new ByteArrayInputStream(bytes);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(inputStream.available());

// 文件名(年月日时分秒+三位随机数+文件后缀)
int random = (int)(Math.random() * 900 + 100);
String newName = formatter.format(LocalDateTime.now()) + random + ".jpg";
// 文件夹
String folderName = "XXXXX/" + ymFormatter.format(LocalDateTime.now()) + "/";
String fileName = folderName + newName;
fileUrl = uploadFileStream(inputStream,fileName);
//base64图片上传限制大小
public static byte[] imageBase64ToByteArray(String base64Str,long size) {
    //判断是否包含前缀,去掉前缀
    if (base64Str.contains(",")) {
        base64Str = base64Str.split(",")[1];
    }
    byte[] decodeFromString = Base64.decodeBase64(base64Str);
    System.out.println("验证base64图片大小:base64:"+ base64Str+" 限制大小:"+size);
    if (decodeFromString.length / 1024 > size) {
        throw new RuntimeException("图片过大");
    }
    return decodeFromString;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值