| | |
| | | import com.alibaba.fastjson2.JSONObject; |
| | | import com.yami.trading.common.exception.BusinessException; |
| | | import com.yami.trading.common.exception.YamiShopBindException; |
| | | import com.yami.trading.common.util.PropertiesUtil; |
| | | import com.yami.trading.service.AwsS3OSSFileService; |
| | | import lombok.extern.slf4j.Slf4j; |
| | | import net.coobird.thumbnailator.Thumbnails; |
| | |
| | | @Service |
| | | @Slf4j |
| | | public class AwsS3OSSFileServiceImpl implements AwsS3OSSFileService { |
| | | |
| | | @Value("${oss.aws.s3.bucketName}") |
| | | private String bucketName; |
| | | // |
| | |
| | | if (StrUtil.isEmpty(fileType) || fileType.contains("blob")) { |
| | | fileType = "blob.png"; |
| | | } |
| | | |
| | | // 生成唯一的文件名 |
| | | String id = UUID.randomUUID().toString(); |
| | | String path = moduleName + "/" + LocalDate.now() + "/" + id + fileType; |
| | | log.info("AwsS3OSSFileService putS3Object bucketName:{},objectKey:{},objectPath:{}", bucketName, path, file.getName()); |
| | | String path = LocalDate.now() + "/" + id + fileType; |
| | | |
| | | // 确保目标文件夹存在 |
| | | File targetDir = new File(PropertiesUtil.getProperty("loca.images.dir") + "/" + LocalDate.now()); |
| | | if (!targetDir.exists()) { |
| | | targetDir.mkdirs(); |
| | | } |
| | | |
| | | // 构建本地文件路径 |
| | | File localFile = new File(targetDir, id + fileType); |
| | | |
| | | // 打印上传路径 |
| | | log.info("LocalFileUploadService uploadFile localFilePath: {}", localFile.getAbsolutePath()); |
| | | |
| | | try { |
| | | // 将文件保存到本地 |
| | | file.transferTo(localFile); |
| | | |
| | | // 如果需要自定义元数据,可以在此处理 |
| | | Map<String, String> metadata = new HashMap<>(); |
| | | metadata.put("x-amz-meta-myVal", "test"); |
| | | PutObjectRequest putOb = PutObjectRequest.builder() |
| | | .bucket(bucketName) |
| | | .key(path) |
| | | .metadata(metadata) |
| | | .build(); |
| | | S3Client s3Client = getS3Client(); |
| | | s3Client.putObject(putOb, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); |
| | | metadata.put("x-amz-meta-myVal", "test"); // 如果需要元数据,可以放在文件名或其他地方 |
| | | |
| | | // 返回相对路径 |
| | | return path; |
| | | } catch (S3Exception e) { |
| | | log.error("AwsS3OSSFileService putS3Object S3Exception", e.getMessage(), e.awsErrorDetails().errorMessage(), e); |
| | | throw new YamiShopBindException("文件上传失败"); |
| | | |
| | | } catch (IOException e) { |
| | | log.error("AwsS3OSSFileService putS3Object IOException", e.getMessage(), e); |
| | | log.error("LocalFileUploadService uploadFile IOException", e.getMessage(), e); |
| | | throw new YamiShopBindException("文件上传失败"); |
| | | } |
| | | } |