package com.example.tlias.conller; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.example.tlias.Resource.aliastilias; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.util.UUID; /** * 阿里云 OSS 工具类 */ @Component @NoArgsConstructor public class AliOSSUtils { String dizhi = "https://"; @Autowired aliastilias dj ; // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。 // 填写Bucket名称,例如examplebucket。 public String upload (String file) { int i = file.lastIndexOf("."); String substring = file.substring(i); String s = UUID.randomUUID().toString(); // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 String objectName = s + substring ; // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。 String filePath= file ; // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(dj.getEndpoint(), dj.getAccessKeyId(), dj.getAccessKeySecret()); try { InputStream inputStream = new FileInputStream(filePath); // 创建PutObject请求。 ossClient.putObject(dj.getBucketName(), objectName, inputStream); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (Exception ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } File deletesc = new File("D:\\临时文件夹"); File[] files = deletesc.listFiles(); for (File file1 : files) { file1.delete(); } // https://tiliassss.oss-cn-beijing.aliyuncs.com/10.png // "C:\\Users\\LX\\Desktop\\PS\\图片\\74f424cafa9a72ca07f4318d98af024.png"; return dizhi + dj.getBucketName()+"."+ dj.getEndpoint()+"/"+ objectName; } }
实现阿里云上传图片代码工具类
于 2024-01-10 22:41:18 首次发布