当前位置:   article > 正文

【SpringBoot】-- 实现本地文件/图片上传到服务器生成url地址_本地图片如何生成url

本地图片如何生成url

        在java项目中你可能会有以下需求:用户上传本地图片,然后展示在网页上。本篇文章将使用阿里云oss实现上传图片到oss,oss生成url。

一、准备工作

首先进入阿里云,按如下操作

进入创建页面,修改读写权限为公共读

然后进入bucket,创建AccessKey

创建后,保存好AccessKeyID和AccessKey Secret

二、代码

将以下依赖添加到项目的pom.xml文件中

  1. <dependency>
  2. <groupId>com.aliyun.oss</groupId>
  3. <artifactId>aliyun-sdk-oss</artifactId>
  4. <version>3.15.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>javax.xml.bind</groupId>
  8. <artifactId>jaxb-api</artifactId>
  9. <version>2.3.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>javax.activation</groupId>
  13. <artifactId>activation</artifactId>
  14. <version>1.1.1</version>
  15. </dependency>
  16. <!-- no more than 2.3.3-->
  17. <dependency>
  18. <groupId>org.glassfish.jaxb</groupId>
  19. <artifactId>jaxb-runtime</artifactId>
  20. <version>2.3.3</version>
  21. </dependency>

创建一个工具类,用于配置aliyunoss

添加以下代码:(注意修改)

  1. import com.aliyun.oss.ClientException;
  2. import com.aliyun.oss.OSS;
  3. import com.aliyun.oss.OSSClientBuilder;
  4. import com.aliyun.oss.OSSException;
  5. import com.aliyun.oss.model.PutObjectRequest;
  6. import com.aliyun.oss.model.PutObjectResult;
  7. import java.io.FileInputStream;
  8. import java.io.InputStream;
  9. public class AliOssUtil {
  10. // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
  11. private static final String ENPOINT = "地区";
  12. // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
  13. // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
  14. private static final String ACCESS_KEY_ID="你的ID";
  15. private static final String ACCESS_KEY_SECRT="KEY";
  16. // 填写Bucket名称,例如examplebucket。
  17. private static final String BUCKETNAME = "你的bucket名称";
  18. public static String uploadFile(String objectName, InputStream in) throws Exception {
  19. // 创建OSSClient实例。
  20. OSS ossClient = new OSSClientBuilder().build(ENPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRT);
  21. String url = "";
  22. try {
  23. // 填写字符串。
  24. String content = "Hello OSS,你好世界";
  25. // 创建PutObjectRequest对象。
  26. PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName,in);
  27. // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
  28. // ObjectMetadata metadata = new ObjectMetadata();
  29. // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
  30. // metadata.setObjectAcl(CannedAccessControlList.Private);
  31. // putObjectRequest.setMetadata(metadata);
  32. // 上传字符串。
  33. PutObjectResult result = ossClient.putObject(putObjectRequest);
  34. //url组成:http://bucket名称.区域节点
  35. url = "https://" + BUCKETNAME + "." + ENPOINT.substring(ENPOINT.lastIndexOf("/")+1)+"/"+objectName;
  36. } catch (OSSException oe) {
  37. System.out.println("Caught an OSSException, which means your request made it to OSS, "
  38. + "but was rejected with an error response for some reason.");
  39. System.out.println("Error Message:" + oe.getErrorMessage());
  40. System.out.println("Error Code:" + oe.getErrorCode());
  41. System.out.println("Request ID:" + oe.getRequestId());
  42. System.out.println("Host ID:" + oe.getHostId());
  43. } catch (ClientException ce) {
  44. System.out.println("Caught an ClientException, which means the client encountered "
  45. + "a serious internal problem while trying to communicate with OSS, "
  46. + "such as not being able to access the network.");
  47. System.out.println("Error Message:" + ce.getMessage());
  48. } finally {
  49. if (ossClient != null) {
  50. ossClient.shutdown();
  51. }
  52. }
  53. return url;
  54. }
  55. }

然后在控制类中使用

  1. @RestController
  2. public class FileUploadController {
  3. @PostMapping("/upload")
  4. public Result<String> upload(MultipartFile file) throws Exception {
  5. String originalFilename = file.getOriginalFilename();
  6. //保证文件名字唯一,防止文件覆盖
  7. String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
  8. String url = AliOssUtil.uploadFile(filename,file.getInputStream());
  9. return Result.success(url);
  10. }
  11. }

三、测试接口

这里使用apifox进行测试

发送请求后,可以看到图片已经存储到oss上,并且返回了地址。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/749627
推荐阅读
相关标签
  

闽ICP备14008679号