2

我是 API/Rest 端点的新手,所以请原谅我在这个主题上缺乏经验。

我正在使用 .net 核心 3.1。我的任务是编写一个端点,除了两个参数一个字符串和一个文件..

该文件将是二进制数据(一种 .bci 文件格式,我假设它是一种自定义格式,但它基本上是一个 .txt 文件,已更改为 .bci 用于机器)

我需要获取文件,然后使用 stringReader 读取文件并保存到本地文件。我再次对端点和读取二进制数据不熟悉,有人可以帮忙吗?我今天一直在寻找整个互联网,但没有占上风。

我知道下面的代码是不正确的,但在这方面真的很挣扎。任何帮助将不胜感激。

//GET: api/ProcessResultsFiles]
        [HttpGet]
        public async Task<IActionResult> ProcessResults(IFormFile file, string bench)
        {
            await ReadData(file);
            return Ok();
        }

        private static Task<byte[]> ReadData(IFormFile benchNameFile)
        {
            using (StringReader sr = new StringReader(benchNameFile))
            {
                string input = null;
                while ((input = sr.ReadLine()) != null)
                {
                    Console.WriteLine(input);
                }
            }
        }
4

1 回答 1

0

根据您的描述,我假设您想将文件上传到物理存储/文件夹,之后您可能想将文件下载到本地,如果是这种情况,您可以参考以下示例:

    [HttpPost("upload")]
    public IActionResult Upload(List<IFormFile> formFiles, string subDirectory)
    {
        try
        {
            subDirectory = subDirectory ?? string.Empty;
            var target = Path.Combine(_environment.WebRootPath, subDirectory);

            if(!Directory.Exists(target))
                Directory.CreateDirectory(target);

            formFiles.ForEach(async file =>
            {
                if (file.Length <= 0) return;
                var filePath = Path.Combine(target, file.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
            });

            return Ok("Upload success!");
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
    [HttpPost("download")]
    public IActionResult DownLoad( string subDirectory,   string filename)
    { 
        //Build the File Path.
        string path = Path.Combine(_environment.WebRootPath, subDirectory +"/"+ filename);

        if (System.IO.File.Exists(path))
        { 
            //Read the File data into Byte Array.
            byte[] bytes = System.IO.File.ReadAllBytes(path);
            //download the file.
            return File(bytes, "application/octet-stream", filename);
        }
        else
        {
            return Ok("file not exist");
        }
    }

结果如下:

在此处输入图像描述

更多关于asp.net core上传文件的详细信息,可以参考以下文章:

在 ASP.NET Core 中上传文件

使用 Web API 上传和下载多个文件

从以上文章中,上传文件时,如果要保存字节数组,可以参考以下代码:

public async Task<IActionResult> OnPostUploadAsync()
{
    using (var memoryStream = new MemoryStream())
    {
        await FileUpload.FormFile.CopyToAsync(memoryStream);

        // Upload the file if less than 2 MB
        if (memoryStream.Length < 2097152)
        {
            var file = new AppFile()
            {
                Content = memoryStream.ToArray()
            };

            _dbContext.File.Add(file);

            await _dbContext.SaveChangesAsync();
        }
        else
        {
            ModelState.AddModelError("File", "The file is too large.");
        }
    }

    return Page();
}
于 2021-08-06T07:05:06.033 回答