我仍然不太了解aws s3存储,但我已经可以使用nuget awssdks进行列出/上传/下载对象的基本操作。
但是,当下载一个对象时,我必须在我的web服务器上创建一个文件,然后使该文件可供我的用户使用。
我似乎不知道如何执行直接下载到客户端。
这可能吗?如果是,该怎么做?
如何简单地转换我的当前源代码直接下载到S3 ?
非常感谢您的指导。
private void DOWFile(string pFileDir, string pFileName, string pDescription)
{
//Armazena o path do arquivo
string lFilePath = pFileDir + pFileName;
//Verifica se o arquivo existe
if (File.Exists(lFilePath))
{
//Limpa o objeto de resposta
Response.Clear();
//Limpa o nome do arquivo
if (Request.UserAgent.Contains("Firefox")) pDescription = TFileInfo.CONVERTToFileName(pDescription);
//Adiciona o cabeçalho do donwload
Response.AddHeader("Content-Disposition", "attachment; filename="" + HttpUtility.UrlPathEncode(pDescription) + """);
//Seta o tipo do arquivo
Response.ContentType = "application/octet-stream";
//Passa a referência do arquivo
Response.WriteFile(lFilePath);
//Executa o download do arquivo
Response.Flush();
//Finaliza o processamento
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
//Mostra a mensagem de Erro
SETErrorInfo(new TErrorInfo(-1, "DOWFile", TErrorInfo.ErrFileNotFound, "FileNotFound - " + lFilePath, false, true, false, true, false, TErrorInfo.TErrType.etLogic));
}
}
public bool FileDownS3(string pLocalPath, string pFileNameS3)
{
IAmazonS3 lClient_Aws = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
TransferUtility lUtility = new TransferUtility(lClient_Aws);
string filename = pLocalPath + pFileNameS3;
FileStream fs = File.Create(filename);
fs.Close();
lUtility.Download(filename, gBucketName, pFileNameS3);
return true;
}
您需要从处理程序操作返回从MemoryStream
创建的File
对象,而不需要将其保存在本地任何地方
为此,首先需要以MemoryStream
的形式获取S3对象。
通过bucketName
&将S3对象的key
设置为AmazonS3Client.GetObjectAsync(...)
,它返回类型为GetObjectResponse
的响应。
GetObjectResponse
有一个属性叫做ResponseStream
。
这是一个继承自Amazon.S3.Model.StreamResponse
的流对象。
你可以复制到MemoryStream
:
GetObjectResponse response = await s3Client.GetObjectAsync(bucketName, keyName);
MemoryStream memoryStream = new MemoryStream();
using (Stream responseStream = response.ResponseStream)
responseStream.CopyTo(memoryStream);
}
一旦复制,返回转换为File
在您的控制器动作。
确保还设置了文件名(File(...)
的第三个参数,以便浏览器可以确定下载的文件类型:
public async Task<IActionResult> DownloadS3File() {
...
return File(memoryStream.ToArray(), "application/octet-stream", "filename.pdf");
}
这将触发从Amazon S3下载的对象的下载。