Convert a file from to Base64 using JavaScript and converting it back to file using C#

前端 未结 2 413
长发绾君心
长发绾君心 2021-01-27 02:57

I am trying to convert pdf and image files to base 64 using javascript and convert it back to file using C# in WEB API.

Javascript

var filesSelected = do         


        
相关标签:
2条回答
  • 2021-01-27 03:14

    Because the FileReader.readAsDataURL() produces a string that is prefixed with extra metadata (the "URL" portion), you need to strip it off on the C# side. Here's some sample code:

    // Sample string from FileReader.readAsDataURL()
    var base64 = "data:image/jpeg;base64,ba9867b6a86ba86b6a6ab6abaa====";
    
    // Some known piece of information that will be in the above string
    const string identifier = ";base64,";
    
    // Find where it exists in the input string
    var dataIndex = base64.IndexOf(identifier);
    
    // Take the portion after this identifier; that's the real base-64 portion
    var cleaned = base64.Substring(dataIndex + identifier.Length);
    
    // Get the bytes
    var bytes = Convert.FromBase64String(cleaned);
    

    You could condense this down if it's too verbose, I just wanted to explain it step by step.

    var bytes = Convert.FromBase64String(base64.Substring(base64.IndexOf(";base64,") + 8));    
    
    0 讨论(0)
  • 2021-01-27 03:22

    According to MDN: FileReader.readAsDataURL those generated URLs are prefixed with something like data:image/jpeg;base64,. Have a look at your generated string. Look for the occurence of base64, and take the base64 data that starts after this prefix.

    0 讨论(0)
提交回复
热议问题