reading a web api blob into a string that I can se

2020-07-25 02:25发布

问题:

i'm trying to turn a wav file into a string I can send to the server as a part of a json object, so that on the server I can turn that string back into a file.

i have tried to use readAsBinaryString and read as text, can't get past error in reading the string into a byte array.

 reader.onloadend = saveMedia;
 reader.readAsText(Blob);
 //reader.readAsBinaryString(Blob); also tried.

then the callback sends an ajax request with an object holding the string in "reader.result" and on the server i tried things like:

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); 
byte[] BinaryData = encoding.GetBytes(stringFromRequest);

the answers to this question below seem to be that this should not be done. but i really want to do it this way because of another tool I am using (breeze js). don't want to use a separate post action with a file data type.

releted: File API - Blob to JSON

回答1:

Found a way that works:

  var reader = new FileReader();
  reader.onloadend = afterRead;
  reader.readAsBinaryString(blob);

function afterRead() {
// convert binary string to base64 for a safe transfer to the server.       
   entity.BinaryProp = window.btoa(reader.result);       
}

on the server-side:

string BinaryString = (string)entityInfo.UnmappedValuesMap["BinaryProp"];
byte[] BinaryData = Convert.FromBase64String(BinaryString);  


回答2:

You can use fileReader.readAsDataURL(fileObject), this encode blob to base64, which can safely upload to server by API.

var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
    let thumbnail = reader.result;
    console.log(thumbnail)
    //send to API
};


回答3:

The answer above is great, but there is a simpler way.

var reader = new FileReader();
reader.onloadend = afterRead;
reader.readAsDataURL(blob);               // Use this function instead

function afterRead() {
    entity.BinaryProp = reader.result;    //result is already a base64 string!
}

See documentation here: FileReader.readAsDataURL()