Upload file to Amazon S3 without SDK: 将文件上传到Amazon S3而无需使用SDK。

huangapple go评论81阅读模式
英文:

Upload file to Amazon S3 without SDK

问题

Sure, here's the translation:

我的Java项目没有使用Maven或任何依赖项。是否有一种纯Java代码的简单方法来将文本文件上传到我的Amazon S3存储桶?这不是一个作业项目。

英文:

My Java project is not set up with Maven or any dependencies. Is there an easy way to upload a text file to my Amazon S3 bucket with pure Java code? This is not a homework project.

答案1

得分: 1

你可以使用位于java.net包中的HttpURLConnection类来调用S3 REST端点。以下是一个使用PUT S3端点上传png文件的示例(在localstack上进行了测试):

英文:

You can use the HttpURLConnection class, included in the java.net package, to call the S3 REST endpoints.

Here's a sample that uploads a png file using the PUT S3 endpoint (tested with localstack):

  1. import java.io.BufferedOutputStream;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.nio.file.Files;
  8. import java.nio.file.Path;
  9. import java.nio.file.Paths;
  10. import java.time.LocalDateTime;
  11. import java.time.ZoneOffset;
  12. import java.time.format.DateTimeFormatter;
  13. public class S3Uploader {
  14. // Example AWS region
  15. private static final String REGION = "eu-central-1";
  16. // <localstack_endpoint>/<bucket_name>
  17. // For real S3, use <bucket-name>.s3.<aws_region>.amazonaws.com
  18. private static final String BUCKET_ENDPOINT = "http://localhost:4566/uploadtest";
  19. // key of the object to save
  20. private static final String OBJECT_NAME = "object.png";
  21. public static void main(String[] args) throws IOException {
  22. // File in the example is in the current dir
  23. Path file = Paths.get(OBJECT_NAME);
  24. String type;
  25. long fileSize;
  26. try {
  27. // Probe content type and size
  28. type = Files.probeContentType(file);
  29. fileSize = Files.size(file);
  30. } catch (IOException e) {
  31. System.err.println("Cannot analyze file " + OBJECT_NAME + "!");
  32. e.printStackTrace();
  33. return;
  34. }
  35. URL url = new URL(BUCKET_ENDPOINT + "/" + OBJECT_NAME);
  36. HttpURLConnection httpConnection;
  37. try {
  38. // Connect to S3
  39. httpConnection = (HttpURLConnection) url.openConnection();
  40. } catch (IOException e) {
  41. System.err.println("Cannot connect to bucket " + BUCKET_ENDPOINT + "!");
  42. e.printStackTrace();
  43. return;
  44. }
  45. httpConnection.setRequestMethod("PUT");
  46. httpConnection.setRequestProperty("Host", BUCKET_ENDPOINT);
  47. httpConnection.setRequestProperty("Content-Type", type);
  48. httpConnection.setRequestProperty("Content-Length", String.valueOf(fileSize));
  49. String datetime = LocalDateTime.now().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssZ"));
  50. // Example AWS headers
  51. // More: https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html
  52. httpConnection.setRequestProperty("x-amz-date", datetime);
  53. httpConnection.setRequestProperty("x-amz-server-side-encryption", "AES256");
  54. httpConnection.setRequestProperty("x-amz-tagging", "description=triangle");
  55. // Authorization (IAM authentication)
  56. // You must sign the request manually
  57. // Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html
  58. httpConnection.setRequestProperty("Authorization", "AWS4-HMAC-SHA256 " +
  59. // Credential=<access_key_id>/<date_in_yyyyMMdd_format>/<aws_region>/<aws_service>/aws4_request
  60. "Credential=abc123/" + datetime.substring(0, datetime.indexOf('T')) + "/" + REGION + "/s3/aws4_request," +
  61. // Headers used in sign process
  62. "SignedHeaders=host;content-type;x-amz-server-side-encryption;x-amz-date;x-amz-tagging," +
  63. // 256-bit signature (you must calculate it manually)
  64. // this is an example
  65. "Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024");
  66. // Write the object to S3
  67. // and read the response, if failure
  68. httpConnection.setDoInput(true);
  69. httpConnection.setDoOutput(true);
  70. try(BufferedOutputStream outstream = new BufferedOutputStream(httpConnection.getOutputStream())) {
  71. // Write the file to S3
  72. Files.copy(file, outstream);
  73. } catch(IOException e) {
  74. System.err.println("Cannot send object to bucket " + BUCKET_ENDPOINT + "!");
  75. e.printStackTrace();
  76. httpConnection.disconnect();
  77. return;
  78. }
  79. int responseStatus = httpConnection.getResponseCode();
  80. if (responseStatus == 200) {
  81. // Success
  82. System.out.println(OBJECT_NAME + " uploaded successfully to bucket " + BUCKET_ENDPOINT + "!");
  83. } else {
  84. // Failure
  85. System.out.println(OBJECT_NAME + " upload failed!");
  86. System.out.println("Status " + responseStatus);
  87. System.out.println("Response:");
  88. System.out.println();
  89. try(BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()))) {
  90. String line;
  91. while ((line = reader.readLine()) != null) {
  92. System.out.println(line);
  93. }
  94. } catch(IOException e) {
  95. System.err.println("Cannot read from " + BUCKET_ENDPOINT + "!");
  96. e.printStackTrace();
  97. }
  98. }
  99. // Close the connection to S3
  100. httpConnection.disconnect();
  101. }
  102. }

As you can see, you need a lot of manual work to interact with S3 through the REST API, as opposed to using the AWS SDK, especially for authentication.

On the IAM part, I inserted mock values: you must sign the request with AWS Signature Version 4.

huangapple
  • 本文由 发表于 2023年5月18日 12:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定