OSS:阿里云图片文件上传

Bertha 。 2024-03-22 12:15 131阅读 0赞

阿里云图片文件上传

依赖
  1. <!-- <dependency>-->
  2. <!-- <groupId>com.alibaba.cloud</groupId>-->
  3. <!-- <artifactId>spring-cloud-starter-alicloud-oss</artifactId>-->
  4. <!-- </dependency>-->
  5. <dependency>
  6. <groupId>com.aliyun.oss</groupId>
  7. <artifactId>aliyun-sdk-oss</artifactId>
  8. <version>3.13.2</version>
  9. <scope>compile</scope>
  10. </dependency>
代码
  1. import com.aliyun.oss.OSSClient;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiImplicitParam;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.cloud.context.config.annotation.RefreshScope;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import org.springframework.web.multipart.MultipartFile;
  11. @Api(tags = {
  12. "图片上传通用接口"})
  13. @RestController
  14. @RefreshScope
  15. public class FileUploadController {
  16. @Autowired
  17. private OSSClient ossClient;
  18. @Value("${bucketName}")
  19. private String bucketName;
  20. @Value("${spring.cloud.alicloud.oss.endpoint}")
  21. private String endpoint;
  22. @PostMapping("/fileUpload")
  23. public Result fileUpload(@RequestParam("file") MultipartFile multipartFile){
  24. Result result = new Result();
  25. //设置图片上传的文件名称
  26. String fileName = System.currentTimeMillis()+"_"+multipartFile.getOriginalFilename();
  27. //执行图片上传
  28. try {
  29. ossClient.putObject(bucketName,fileName,multipartFile.getInputStream());
  30. //拼接文件路径进行返回
  31. String logoPath = "https://"+bucketName+"."+endpoint+"/"+fileName;
  32. result.setData(logoPath);
  33. result.setStatus(ResultCode.success);
  34. result.setDesc("上传成功");
  35. return result;
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. result.setStatus(ResultCode.error);
  39. result.setDesc("上传失败");
  40. return result;
  41. }
  42. }
  43. @PostMapping("/imageUploadResize")
  44. @ApiImplicitParam(paramType = "form", dataType = "file", name = "fileName", value = "上传文件", required = true)
  45. public Result imageUploadResize(@RequestParam("fileName") MultipartFile multipartFile){
  46. Result result = new Result();
  47. String fileName = System.currentTimeMillis()+"_"+multipartFile.getOriginalFilename();
  48. //图片上传
  49. try {
  50. ossClient.putObject(bucketName,fileName,multipartFile.getInputStream());
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. result.setStatus(ResultCode.error);
  54. result.setDesc("图片上传失败");
  55. return result;
  56. }
  57. String imagePath = "https://"+bucketName+"."+endpoint+"/"+fileName+"?x-oss-process=image/resize,m_fill,h_100,w_200";
  58. result.setStatus(ResultCode.success);
  59. result.setDesc("图片上传成功");
  60. result.setData(imagePath);
  61. return result;
  62. }
  63. }

或者

依赖
  1. <dependency>
  2. <groupId>com.alibaba.cloud</groupId>
  3. <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
  4. </dependency>
代码
  1. import com.aliyun.oss.OSS;
  2. import com.aliyun.oss.common.utils.BinaryUtil;
  3. import com.aliyun.oss.model.MatchMode;
  4. import com.aliyun.oss.model.PolicyConditions;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Date;
  11. import java.util.LinkedHashMap;
  12. @RestController
  13. public class OssController {
  14. @Autowired
  15. OSS ossClient;
  16. @Value("${spring.cloud.alicloud.oss.endpoint}")
  17. private String endpoint;
  18. @Value("${spring.cloud.alicloud.oss.bucket}")
  19. private String bucket;
  20. @Value("${spring.cloud.alicloud.access-key}")
  21. private String accessId;
  22. @RequestMapping("/oss/policy")
  23. public R policy() {
  24. //https://gulimall-hello.oss-cn-beijing.aliyuncs.com/hahaha.jpg
  25. String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
  26. // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
  27. // String callbackUrl = "http://88.88.88.88:8888";
  28. String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  29. String dir = format + "/"; // 用户上传文件时指定的前缀。
  30. Map<String, String> respMap = null;
  31. try {
  32. long expireTime = 30;
  33. long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
  34. Date expiration = new Date(expireEndTime);
  35. PolicyConditions policyConds = new PolicyConditions();
  36. policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
  37. policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
  38. String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
  39. byte[] binaryData = postPolicy.getBytes("utf-8");
  40. String encodedPolicy = BinaryUtil.toBase64String(binaryData);
  41. String postSignature = ossClient.calculatePostSignature(postPolicy);
  42. respMap = new LinkedHashMap<String, String>();
  43. respMap.put("accessid", accessId);
  44. respMap.put("policy", encodedPolicy);
  45. respMap.put("signature", postSignature);
  46. respMap.put("dir", dir);
  47. respMap.put("host", host);
  48. respMap.put("expire", String.valueOf(expireEndTime / 1000));
  49. // respMap.put("expire", formatISO8601Date(expiration));
  50. } catch (Exception e) {
  51. // Assert.fail(e.getMessage());
  52. System.out.println(e.getMessage());
  53. }
  54. return R.ok().put("data",respMap);
  55. }
  56. }

或者

依赖
  1. <properties>
  2. <aliyun-sdk-oss.version>2.8.2</aliyun-sdk-oss.version>
  3. <aliyun-sdk-core.version>3.2.8</aliyun-sdk-core.version>
  4. <aliyun-sdk-dysmsapi.version>1.1.0</aliyun-sdk-dysmsapi.version>
  5. </properties>
  6. <dependency>
  7. <groupId>com.aliyun.oss</groupId>
  8. <artifactId>aliyun-sdk-oss</artifactId>
  9. <version>${aliyun-sdk-oss.version}</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.aliyun</groupId>
  13. <artifactId>aliyun-java-sdk-core</artifactId>
  14. <version>${aliyun-sdk-core.version}</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>com.aliyun</groupId>
  18. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  19. <version>${aliyun-sdk-dysmsapi.version}</version>
  20. </dependency>
代码
  1. import com.aliyun.oss.OSSClient;
  2. import com.aliyun.oss.model.PutObjectResult;
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.InputStream;
  9. import java.net.URL;
  10. import java.util.Date;
  11. /**
  12. * 阿里云配置
  13. */
  14. @Configuration
  15. public class AliyunConfig {
  16. @Value("${file.aliyun.endpoint}")
  17. private String endpoint;
  18. @Value("${file.aliyun.accessKeyId}")
  19. private String accessKeyId;
  20. @Value("${file.aliyun.accessKeySecret}")
  21. private String accessKeySecret;
  22. /**
  23. * 阿里云文件存储client
  24. */
  25. @Bean
  26. public OSSClient ossClient() {
  27. OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
  28. return ossClient;
  29. }
  30. public static void main(String[] args) throws FileNotFoundException {
  31. OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com", "LTAI3jTQMjLamd0v", "aOR1ZFUoJCKmiSUUQopZcwZDu0uei6");
  32. InputStream inputStream = new FileInputStream("D://ssfw.sql");
  33. ossClient.putObject("topwulian", "upload/" + "ss11fw.sql", inputStream);
  34. Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
  35. // 生成URL
  36. URL url = ossClient.generatePresignedUrl("topwulian", "upload/" + "ss11fw.sql", expiration);
  37. System.out.println(url);
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,131人围观)

还没有评论,来说两句吧...

相关阅读

    相关 阿里oss图片

    背景 上周接到一个新的需求,要在客户端上报图片信息,以前是存在七牛上,现在要全部转到阿里云的oss上,然后那周基本都在啃阿里云的官方文档,最后完成了这个需求,现在来分享一

    相关 图片阿里oss保存

    互联网新时代,除了纯信息展示类的网站,基本都是有文件上传功能的。但是随着业务的发展,如果上传的文件和数据库都和网站程序源代码放在一起,那是有相当多的弊端的。 1:用户体验比较