要通过ASP.NET Core从对象存储中下载文件,可以按照以下步骤进行操作:
"QCloudCosOptions": {
"SecretId": "YourSecretId",
"SecretKey": "YourSecretKey",
"Bucket": "YourBucket",
"Region": "YourRegion"
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using QCloud.CosApi.Sdk;
[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
private readonly QCloudCosOptions _cosOptions;
public FileController(IOptions<QCloudCosOptions> cosOptions)
{
_cosOptions = cosOptions.Value;
}
[HttpGet("{fileName}")]
public IActionResult DownloadFile(string fileName)
{
var cos = new CosCloud(_cosOptions.SecretId, _cosOptions.SecretKey);
var result = cos.DownloadFile(_cosOptions.Bucket, fileName);
if (result.Code == 0)
{
return File(result.Data, "application/octet-stream", fileName);
}
else
{
return BadRequest(result.Message);
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<QCloudCosOptions>(Configuration.GetSection("QCloudCosOptions"));
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
以上步骤完成后,可以通过发送HTTP GET请求到/api/file/{fileName}
的URL来下载对象存储中的文件。如果文件存在且下载成功,将返回文件的字节流;否则,将返回错误信息。
领取专属 10元无门槛券
手把手带您无忧上云