如何将文件转换成内存中的字节数组?

这是我的代码:

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

现在我要用下面的代码把这个文件转换成字节数组:

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

然后我把这段代码上传到 nosql 数据库。一切正常,但问题是我不想保存文件。相反,我想直接上传文件到我的数据库。如果我可以直接把文件转换成字节数组,而不用保存它,那就有可能了。

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
}
148119 次浏览

You can use the following code to convert it to a byte array:

foreach (var file in files)
{
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
using (var reader = new StreamReader(file.OpenReadStream()))
{
string contentAsString = reader.ReadToEnd();
byte[] bytes = new byte[contentAsString.Length * sizeof(char)];
System.Buffer.BlockCopy(contentAsString.ToCharArray(), 0, bytes, 0, bytes.Length);
}
}
}

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

You can just write a simple extension:

public static class FormFileExtensions
{
public static async Task<byte[]> GetBytes(this IFormFile formFile)
{
await using var memoryStream = new MemoryStream();
await formFile.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
}

Usage

var bytes = await formFile.GetBytes();
var hexString = Convert.ToBase64String(bytes);

You can retrieve your file by using the Request.Form already implemented (as image for instance) :

var bytes = new byte[Request.Form.Files.First().Length];
var hexString = Convert.ToBase64String(bytes);

Hope it help