我使用AWS S3构建webapp。
问题:如何从S3下载文件并将文件保存在用户下载文件夹中?
到目前为止我的代码:
this.getS3().getObject({Bucket:bucket_name, Key:keys},
function(error, data) {
if (error) {
console.log("Error!")
} else {
// How to save 'data' file in Download folder?
}
});
答案 0 :(得分:0)
这就是我在.NET中使用适用于.Net的AWS SDK的方式
public class AmazonS3
{
//Local varaibles to get the accesskey and secretkey
private readonly string accessKey;
private readonly string secretKey;
private RegionEndpoint regionEndpoint;
AmazonS3Client client = null;
TransferUtility utility = null;
/// <summary>
/// Class Constructor for getting the accesskey and secretkey for the Amazon S3 bucket
/// </summary>
public AmazonS3Operations()
{
//get the accesskey and secretkey from the web.config
accessKey = ConfigurationManager.AppSettings["AWSS3AccessKey"];
secretKey = ConfigurationManager.AppSettings["AWSS3SecretKey"];
regionEndpoint = RegionEndpoint.GetBySystemName(ConfigurationManager.AppSettings["AWSS3RegionEndPoint"]);
//Initialize the connection here and use it every where in a singleton model
client = GetS3ClientConnection();
}
public byte[] GetFileObject(string filePath, string fileNameInS3, out string strContentType)
{
byte[] data = null;
GetObjectRequest request = new GetObjectRequest();
request.BucketName = filePath;
request.Key = fileNameInS3;
//get the object response here
GetObjectResponse response = client.GetObject(request);
using (MemoryStream ms = new MemoryStream())
{
response.ResponseStream.CopyTo(ms);
data = ms.ToArray();
}
//get the Mimetype here
strContentType = MimeMapping.GetMimeMapping(fileNameInS3);
return data;
}
}
将您的参数传递给方法GetFileObject
,方法将返回byte[]
数组作为响应。在用户下载文件夹中创建具有相应名称和MIME类型的相应文件。
请参阅此处以了解与Java相同的内容:http://docs.aws.amazon.com/AmazonS3/latest/dev/RetrievingObjectUsingJava.html
其他语言也可以在线获取其他AWS文档。