Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

asp.net core - Trying to convert a base64String into a IFormFile throws SystemInvalidOperation exception in C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are implicitly calling Dispose on the MemoryStreams after you pass them to the FormFile constructor due to the using block. You then return a list of FormFile objects where the inner streams are all disposed.

FormFile does not make a copy of the stream's content, but instead (via ReferencedReadStream) calls methods like Stream.Read which (in the case of MemoryStream at least) will throw an exception if the stream has been closed--which it has due to Dispose.

You've not provided any information such as a stack trace so this is a best guess, but removing the using block should suffice to fix this problem.

private List<IFormFile> Base64ToImage(List<EquipmentFile> equipmentFiles)
{
    List<IFormFile> formFiles = new List<IFormFile>();
    foreach (var eqp in equipmentFiles)
    {
        
        byte[] bytes = Convert.FromBase64String(eqp.File);
        MemoryStream stream = new MemoryStream(bytes);
        
        IFormFile file = new FormFile(stream, 0, bytes.Length, eqp.Name, eqp.Name);
        formFiles.Add(file);
        
    }
    return formFiles;
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...