当前位置:   article > 正文

AWS S3 实现预签名上传_aws 签名上传

aws 签名上传

步骤:

1、前端上传文件,将要上传的文件名称传到后台

2、后台通过该文件名称生成预上传URL返回前端

3、前端请求该URL,并携带文件上传至S3

后端代码

  1. /**
  2. * AWS预签名上传
  3. * @return
  4. */
  5. @GetMapping("/upload")
  6. public Object generatePreSignedUrl(String fileName){
  7. Map<String, Object> map = new HashMap<>();
  8. try {
  9. AWSCredentials awsCredentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
  10. AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
  11. AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
  12. .withCredentials(new ProfileCredentialsProvider())
  13. .withRegion(Regions.CN_NORTH_1)
  14. .withCredentials(awsCredentialsProvider)
  15. .build();
  16. java.util.Date expiration = new java.util.Date();
  17. long expTimeMillis = expiration.getTime();
  18. expTimeMillis += 1000 * 60 * 30;
  19. expiration.setTime(expTimeMillis);
  20. String name = fileName.substring(0,fileName.lastIndexOf("."));
  21. String fileType = fileName.substring(fileName.lastIndexOf("."));
  22. String prefixFileName = name+ "_"+String.valueOf(System.currentTimeMillis()).substring(6)+""+fileType;
  23. Review review = new Review();
  24. review.setName(name);
  25. GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, prefixFileName)
  26. .withMethod(HttpMethod.PUT)
  27. .withExpiration(expiration);
  28. URL url = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
  29. if(url == null){
  30. return map;
  31. }
  32. // 文件访问地址
  33. StringBuilder urlImage = new StringBuilder();
  34. urlImage.append(url.getProtocol()).append("://").append(url.getHost()).
  35. append(URLDecoder.decode(url.getPath(), "UTF-8"));
  36. // 预签名put地址
  37. StringBuilder preUrl = new StringBuilder();
  38. preUrl.append(url.getProtocol()).append("://").append(url.getHost()).
  39. append(URLDecoder.decode(url.getFile(), "UTF-8"));
  40. map.put("preUrl",preUrl);
  41. map.put("urlImage",urlImage);
  42. return map;
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. return map;
  46. }
  47. }

前端代码

  1. import axios from 'axios'
  2. axios.put(preUrl, fileList[0], {
  3. headers: {
  4. 'Content-Type': 'multipart/form-data'
  5. },
  6. onUploadProgress: progressEvent => {
  7. let complete = (progressEvent.loaded / progressEvent.total * 100.).toFixed(2)
  8. }
  9. })
  10. .then((res: any) => {
  11. if (res.status == 200) {
  12. console.log(res)
  13. }
  14. }).catch(
  15. err => {
  16. console.log(err)
  17. })

当然也可以直接后台就上传到AWS,后端代码为:

  1. private void uploadContent(String imageUrl){
  2. // Set the pre-signed URL to expire after one hour.
  3. java.util.Date expiration = new java.util.Date();
  4. long expTimeMillis = expiration.getTime();
  5. expTimeMillis += 1000 * 60 * 5;
  6. expiration.setTime(expTimeMillis);
  7. // Generate the pre-signed URL.
  8. String fileType = imageUrl.substring(imageUrl.lastIndexOf("."));
  9. // 上传s3不保存后缀,
  10. String prefixFileName = UUIDUtils.getUUID()+""+fileType;
  11. GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, prefixFileName)
  12. .withMethod( com.amazonaws.HttpMethod.PUT)
  13. .withExpiration(expiration);
  14. URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest);
  15. log.info("Generate the pre-signed URL: "+url);
  16. // Create the connection and use it to upload the new object using the pre-signed URL.
  17. HttpsURLConnection connection = null;
  18. OutputStream out = null;
  19. InputStream inputStream = null;
  20. try {
  21. // 需要上传的网络图片转为流
  22. URL url1 = new URL(imageUrl);
  23. HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url1.openConnection();
  24. inputStream = httpsURLConnection.getInputStream();
  25. // 通过预签名url上传文件
  26. connection = (HttpsURLConnection) url.openConnection();
  27. connection.setDoOutput(true);
  28. connection.setRequestMethod("PUT");
  29. out = connection.getOutputStream();
  30. byte[] arr = new byte[1024]; //该数组用来存入从输入文件中读取到的数据
  31. int len; //变量len用来存储每次读取数据后的返回值
  32. //while循环:每次从输入文件读取数据后,都写入到输出文件中
  33. while( ( len=inputStream.read(arr) ) != -1 ) {
  34. out.write( arr, 0, len);
  35. }
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. }finally {
  39. if(out != null){
  40. try {
  41. out.close();
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. if(inputStream != null){
  47. try {
  48. inputStream.close();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. }

参考官方文档:Uploading objects using presigned URLs - Amazon Simple Storage Service

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

闽ICP备14008679号