繁体   English   中英

使用 ASP.NET 核心控制台应用程序从 API 端点下载文件

[英]Download a file using a ASP.NET Core Console Application From API Endpoint

我有一个 API 生成 Word 文档并在使用端点时根据请求提供它们,例如https://myapi.com/GetDocumentById/ {id}

我正在尝试让我的控制台应用程序访问 URL 并将文件保存到本地驱动器,例如 C:\Temp

到目前为止,我遇到的所有解决方案都以我显然没有使用的 MVC 为中心。

有人可以指出我正确的方向吗? 我应该使用什么? 我不能使用 WebClient,因为DownloadFile需要一个文件名,我不一定知道它。 我需要从端点下载生成的文件。

谢谢

 public async Task<string> DownloadFile(string guid) { var fileInfo = new FileInfo($"{guid}.txt"); var response = await _httpClient.GetAsync($"{_url}/api/files?guid={guid}"); response.EnsureSuccessStatusCode(); await using var ms = await response.Content.ReadAsStreamAsync(); await using var fs = File.Create(fileInfo.FullName); ms.Seek(0, SeekOrigin.Begin); ms.CopyTo(fs); return fileInfo.FullName; }

您可以使用HttpClient接收从 api 返回的文件,我创建了一个简单的演示供您参考。

首先,要创建 word 文件,您需要在 api 项目中下载DocumentFormat.OpenXml dll。

Api:

    [Route("api/[controller]")]
    [ApiController]
    public class GetDocumentByIdController : ControllerBase
    {
       [HttpGet("{id}")]
        public IActionResult GenerateDocx(int id)
        {
            using (MemoryStream mem = new MemoryStream())
            {
                using (WordprocessingDocument wordDocument =
        WordprocessingDocument.Create(mem, WordprocessingDocumentType.Document))
                {
                    // Add a main document part. 
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
                    // Create the document structure and add some text.
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());
                    Paragraph para = body.AppendChild(new Paragraph());
                    Run run = para.AppendChild(new Run());
                     run.AppendChild(new Text("The text in docx which created by " + id.ToString()));
                }
                return File(mem.ToArray(), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }
        }
    }

控制台应用程序:

class Program
    {
        static void Main(string[] args)
        {
            try
            {
                UriBuilder builder = new UriBuilder("http://localhost:50855/api/ApiCode/GenerateDocx/1");
                builder.Query = "id=1";// you can pass any other value
                HttpClient client = new HttpClient();
                var contentBytes = client.GetByteArrayAsync(builder.Uri).Result;
                MemoryStream stream = new MemoryStream(contentBytes);
                FileStream file = new FileStream(@"C:\Temp\ABC.docx", FileMode.Create, FileAccess.Write);
                stream.WriteTo(file);
                file.Close();
                stream.Close();
            }
            catch (Exception)
            {
                throw; //throws 'TypeError: Failed to fetch'
            }
        }
    }

运行控制台应用程序后,您会在 C:\Temp 路径下找到a word file named ABC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM