Home > other >  How do i send a input type file as a binary?
How do i send a input type file as a binary?

Time:11-24

I simply want to get my HTML file input as a binary to save it in my SQL SERVER. The code below,apparently solves my problem,but i can't get "reader.readAsBinaryString(input.files[0])" and store in a variable. It just console.log the input.files[0] ,but i need to store it. Also,I'm not used to FileReader(),so any tips on how to use it are welcome.

Does this function uses the actual file being uploaded,or does it get the path to it?

The code is simple:

<input type="file"  id="myFile" name="myFile">

JS:

$("#myFile").change(function (event) {
  var input = event.target;
  var reader = new FileReader();
  reader.onload = function () {
    console.log(reader.result);
  };
  fileToSave = reader.readAsBinaryString(input.files[0]);
});

CodePudding user response:

readAsBinaryString doesn't return anything. What it does do is tell the FileReader to begin reading the file. When that process finishes, you can see the data you're reading in the result property of the FileReader object.

Which you've observed is available in the onload event:

reader.onload = function(){
    console.log(reader.result);
};

Since that event is when the data is available, then that event is where you can read that data. For example:

reader.onload = function(){
    fileToSave = reader.result;
    console.log(fileToSave);
};

Of course then the next question becomes... When/where do you attempt to use the value in fileToSave. Keep in mind that this is an asynchronous operation. If you're trying to use the data in fileToSave right away then of course it won't contain the data that is later available in this onload event.

Whatever operation needs to use that data, that operation would have to happen after this event. For example:

reader.onload = function(){
    fileToSave = reader.result;
    console.log(fileToSave);
    someOtherOperation();
};

or perhaps even:

reader.onload = function(){
    const fileToSave = reader.result;
    console.log(fileToSave);
    someOtherOperation(fileToSave);
};
  • Related