【发布时间】:2026-01-08 05:55:01
【问题描述】:
请检查以下代码
import java.io.File;
import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.PutObjectRequest;
public class UploadObjectSingleOperation {
private static String bucketName = "*******";
private static String keyName = "************";
private static String uploadFileName = "C:/Users/Yohan/Desktop/asdasd.html";
public static void main(String[] args) throws IOException {
BasicAWSCredentials creds = new BasicAWSCredentials(keyName, "**********");
AmazonS3 s3client = AmazonS3ClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(creds)).withRegion(Regions.AP_SOUTH_1).build();
// AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
try {
System.out.println("Uploading a new object to S3 from a file\n");
File file = new File(uploadFileName);
s3client.putObject(new PutObjectRequest(
bucketName, keyName, file));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which " +
"means your request made it " +
"to Amazon S3, but was rejected with an error response" +
" for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which " +
"means the client encountered " +
"an internal error while trying to " +
"communicate with S3, " +
"such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
好的,上面的代码用于将文件上传到 Amazon S3 存储桶。我的 S3 存储桶位于离我的客户端最近的位置 Asia Pacific - Mumbai。
上面的代码工作正常,但是我注意到以下内容。
- 上传的总是
key。真正的文件没有上传。请查看下图。
为什么会这样?当我使用 S3 的 Web 界面上传文件时,它工作得很好。
【问题讨论】:
-
我不认为你的“答案”真的能解决你的问题。在 s3 中,
keyName是您的 object name ,其中包括特殊前缀,如斜杠或反斜杠。它与您的 AWS API 密钥无关。
标签: java amazon-web-services file-upload amazon-s3