1. 程式人生 > >ASP.NET Core Web API實現圖片下載

ASP.NET Core Web API實現圖片下載

前端訪問下載圖片API下載圖片。

一、ASP.NET Core Web API程式碼

方案一:

    [Route("api/[controller]")]
    [ApiController]
    public class DownloadController : BaseController
    {
        // GET: api/Download
        [HttpGet]
        public FileStreamResult Get()
        {
            //方案一  方法返回值:IActionResult,FileResult,FileStreamResult
            FileStream fileStream = new FileStream(Directory.GetCurrentDirectory() + Common.ConfigManager.GetConfigValue("createrFilesPath") + Common.ConfigManager.GetConfigValue("fileName"), FileMode.Open, FileAccess.Read);
            return File(fileStream, "application/octet-stream", Common.ConfigManager.GetConfigValue("fileName"));
        }
    }

注:方法返回值型別可以為IActionResult,FileResult,FileStreamResult中的任意一種。

方案二:

    [Route("api/[controller]")]
    [ApiController]
    public class DownloadController : BaseController
    {
        // GET: api/Download
        [HttpGet]
        public void Get()
        {
            //方案二,方法無返回值,void,當用戶點選下載對話窗上的下載按鈕後會再次請求
            Response.ContentType = "application/octet-stream";
            Response.ContentType = "image/jpeg";
            //通知瀏覽器下載檔案而不是開啟
            Response.Headers.Add("Content-Disposition", "attachment; filename=" + Common.ConfigManager.GetConfigValue("fileName"));
            Response.SendFileAsync(Directory.GetCurrentDirectory() + Common.ConfigManager.GetConfigValue("createrFilesPath") + Common.ConfigManager.GetConfigValue("fileName"));
        }
    }

注:該方案方法不需要返回值型別。需要注意的一點是:瀏覽器彈出下載對話方塊後當用戶點選下載按鈕後瀏覽器會再次請求介面。

方案三:

    [Route("api/[controller]")]
    [ApiController]
    public class DownloadController : BaseController
    {
        // GET: api/Download
        [HttpGet]
        public FileStreamResult Get()
        {
            //方案三
            var addrUrl = Directory.GetCurrentDirectory() + Common.ConfigManager.GetConfigValue("createrFilesPath") + Common.ConfigManager.GetConfigValue("fileName");
            var stream = System.IO.File.OpenRead(addrUrl);
            string fileExt = ".jpg";  // 這裡可以寫一個獲取副檔名的方法,獲取副檔名
            //獲取檔案的ContentType
            var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
            var memi = provider.Mappings[fileExt];
            return File(stream, memi, Path.GetFileName(addrUrl));
        }
    }

注:方案三可以看做方案一的優化,避免了方案一的大量硬編碼

說明:這次實現三個方案中的圖片地址均為固定的一張圖片的地址,採用了實體地址,實際專案中圖片地址可以是實體地址也可以是虛擬地址(網路地址)。