sinfella
sinfella

Reputation: 286

Receiving binary Data from a rest endpoint

I am new to API/Rest endpoints, so please forgive my inexperience on this topic.

I am using .net core 3.1. And i have been tasked to write an endpoint, that excepts two parameters a string and a file..

The file will be of binary data (a .bci file format, which i assume is a custom one, but all it is basically is a .txt file, that has been changed to .bci for a machine)

I need to get the file and then read the file using a stringReader and saved to a file locally. Again i am new to endpoints and reading binary data, can anyone help? i have been looking all over the internet today but with no prevail.

I know the below code is incorrect, but really struggling on this one. Any help would much be appreciated.

//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);
                }
            }
        }

Upvotes: 4

Views: 3939

Answers (1)

Zhi Lv
Zhi Lv

Reputation: 21716

From your description, I assume you want to upload the file to the Physical storage/folder, after that might be you want to download the file to local, if that is the case, you could refer the following sample:

    [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");
        }
    }

The result as below:

enter image description here

More detail information about upload file in asp.net core, you can refer the following articles:

Upload files in ASP.NET Core

Upload And Download Multiple Files Using Web API

From the above articles, when upload file, if you want to save the byte array, you can refer the following code:

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();
}

Upvotes: 4

Related Questions