英文:
Need to get the image from server by API link (The image is published with backend to Aure)
问题
我创建了一个 ASP.NET CORE WEB API 6.0 项目。我创建了一个名为 'Image' 的文件夹,并将 png 图片保存在其中。现在我想通过链接获取这张图片。API 已发布到 AZURE,我想通过链接获取图片,例如 'apilnk/Image/test.png',但似乎我需要先发布这个文件夹。我应该如何配置 app.UseStaticFiles 来实现这一点?或者我需要一些其他的设置。
谢谢。
我期望使用链接 'apiurl/Image/someimage.png' 显示一张图片。
英文:
I created a project ASP NET CORE WEB API 6.0. I created a folder 'Image' and save the png picture there. Now I wont to get this image by link. API was published to AZURE, and I want to get the image by link like 'apilnk/Image/test.png', but looks like I need to make the folder publis first. How can i configure app.UseStaticFiles to do this? Or I need some more settings.
Thank you.
I am expecting to display an image using url 'apiurl/Image/someimage.png'
答案1
得分: 0
可以轻松定义一个操作并处理所有与下载相关的逻辑。此示例代码解释了如何实现这一点。
```csharp
using Microsoft.AspNetCore.StaticFiles;
[ApiController]
[Route("api/[controller]/[action]")]
public class FileDownloadController : ControllerBase
{
private readonly IWebHostEnvironment _environment;
public FileDownloadController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpGet]
[Route("{fileName}")]
public async Task<IActionResult> DownloadImage(string fileName, CancellationToken cancellationToken)
{
var filePath = Path.Combine(_environment.ContentRootPath, "Image", fileName);
var fileAsByteArray = await System.IO.File.ReadAllBytesAsync(filePath, cancellationToken);
var fileProvider = new FileExtensionContentTypeProvider();
if (fileProvider.TryGetContentType(fileName, out string contentType) is false)
{
throw new ArgumentOutOfRangeException($"无法为文件名 {fileName} 找到内容类型。");
}
return File(fileAsByteArray, contentType);
}
}
英文:
You can easily define an action and handle all logic you have for download with that. This sample code explains how you can do that.
using Microsoft.AspNetCore.StaticFiles;
[ApiController]
[Route("api/[controller]/[action]")]
public class FileDownloadController : ControllerBase
{
private readonly IWebHostEnvironment _environment;
public FileDownloadController(IWebHostEnvironment environment)
{
_environment = environment;
}
[HttpGet]
[Route("{fileName}")]
public async Task<IActionResult> DownloadImage(string fileName, CancellationToken cancellationToken)
{
var filePath = Path.Combine(_environment.ContentRootPath, "Image", fileName);
var fileAsByteArray = await System.IO.File.ReadAllBytesAsync(filePath, cancellationToken);
var fileProvider = new FileExtensionContentTypeProvider();
if (fileProvider.TryGetContentType(fileName, out string contentType) is false)
{
throw new ArgumentOutOfRangeException($"Unable to find Content Type for file name {fileName}.");
}
return File(fileAsByteArray, contentType);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论