如何将文件转换为内存中的字节数组? [英] How to convert a file into byte array in memory?

查看:123
本文介绍了如何将文件转换为内存中的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

 public async Task<IActionResult> Index(ICollection<IFormFile> files)
 {
    foreach (var file in files)
        uploaddb(file);   

    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

            await file.SaveAsAsync(Path.Combine(uploads, fileName));
        }
    }
}

现在我正在使用以下代码将此文件转换为字节数组:

Now I am converting this file into byte array using this code:

var filepath = Path.Combine(_environment.WebRootPath, "uploads/Book1.xlsx");
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
string s = Convert.ToBase64String(fileBytes);

然后我将这段代码上传到我的nosql数据库中.一切正常,但是问题是我不想保存文件.与其相反,我想直接将文件上传到我的数据库中.如果我可以不保存就直接将文件直接转换为字节数组,就有可能.

And then I am uploading this code into my nosql database.This is all working fine but the problem is i don't want to save the file. Instead of that i want to directly upload the file into my database. And it can be possible if i can just convert the file into byte array directly without saving it.

public async Task<IActionResult> Index(ICollection<IFormFile> files)
{
    foreach (var file in files)
        uploaddb(file);   
    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');

///Code to Convert the file into byte array
}

推荐答案

与将数据另存为字符串(分配的内存超出所需的数量,并且如果二进制数据中的空字节可能不起作用)相反,我会推荐一种更像

As opposed to saving the data as a string (which allocates more memory than needed and might not work if the binary data has null bytes in it), I would recommend an approach more like

foreach (var file in files)
{
  if (file.Length > 0)
  {
    using (var ms = new MemoryStream())
    {
      file.CopyTo(ms);
      var fileBytes = ms.ToArray();
      string s = Convert.ToBase64String(fileBytes);
      // act on the Base64 data
    }
  }
}

此外,为了他人的利益,可以在

Also, for the benefit of others, the source code for IFormFile can be found on GitHub

这篇关于如何将文件转换为内存中的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆