我需要知道如何在C#、. NET CORE中将byte []转换为IFormFile 你有解决的办法吗?
谢谢。
答案 0 :(得分:1)
源代码FromFile.cs显示它实现了 IFromFile 接口。尽管在处理http请求时可以轻松地从HttpRequest.Form.Files
属性中找到那些文件,但是您仍然可以通过本地文件或已拥有的字节数组创建自定义的 IFromFile 对象。这样的例子,希望会有所帮助。
UnitTest.cs
[Fact]
public async Task FileUploadToStorage_ReturnTrue_Test()
{
var testFilePath = "path/to/test.jpg";
var testFileBytes = File.ReadAllBytes(testFilePath);
var service = new FakeStorageService();
using (var ms = new MemoryStream(testFileBytes))
{
IFormFile fromFile = new FormFile(ms, 0, ms.Length,
Path.GetFileNameWithoutExtension(testFilePath),
Path.GetFileName(testFilePath)
);
var result = await service.Upload(fromFile);
Assert.True(result);
}
}
FakeStorageService.cs
public class FakeStorageService
{
public async Task<bool> Upload(IFormFile file)
{
using (var fs = file.OpenReadStream())
{
return await GetStorage().UploadAsync(fs);
}
}
}