package com.mzl.flower.service.oss; import com.mzl.flower.config.oss.TosOssProperties; import com.mzl.flower.config.exception.ValidationException; import com.mzl.flower.utils.UUIDGenerator; import com.volcengine.tos.TOSV2; import com.volcengine.tos.TosClientException; import com.volcengine.tos.TosServerException; import com.volcengine.tos.model.object.PutObjectFromFileInput; import com.volcengine.tos.model.object.PutObjectFromFileOutput; import com.volcengine.tos.model.object.PutObjectInput; import com.volcengine.tos.model.object.PutObjectOutput; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; @Service public class TosOssService { @Autowired private TOSV2 tosClient; @Autowired private TosOssProperties tosOssProperties; private String upladPre="https://"; public TosOssService(TOSV2 tosClient) { this.tosClient = tosClient; } public String uploadFile(String objectKey, String filePath) throws IOException { try { PutObjectFromFileInput input = new PutObjectFromFileInput() .setBucket(tosOssProperties.getBucketname()).setKey(objectKey).setFilePath(filePath); PutObjectFromFileOutput output = tosClient.putObjectFromFile(input); return "Upload success! ETag: " + output.getEtag(); } catch (TosClientException | TosServerException e) { throw new IOException("Upload failed: " + e.getMessage(), e); } } public String uploadFile(InputStream inputStream, String fileName) throws IOException { try { //获取文件名称 String filename = fileName; //使文件名称唯一 String uuid = UUIDGenerator.getUUID(); filename = uuid + filename; String dir = uuid.substring(0, 2); filename = dir + "/" + filename; PutObjectInput putObjectInput = new PutObjectInput().setBucket(tosOssProperties.getBucketname()).setKey(filename).setContent(inputStream); PutObjectOutput output = tosClient.putObject(putObjectInput); // System.out.println("putObject succeed, object's etag is " + output.getEtag()); // System.out.println("putObject succeed, object's crc64 is " + output.getHashCrc64ecma()); // https://edu-mys.oss-cn-chengdu.aliyuncs.com/yy.JPG String url = upladPre+ tosOssProperties.getBucketname() + "." + tosOssProperties.getEndpoint() + "/" + filename; return url; } catch (TosClientException | TosServerException e) { throw new ValidationException("上传到云服务器发生异常"); } } }