I want JavaScript to obtain data such as PNG images in binary format.

Asked 2 years ago, Updated 2 years ago, 101 views

I have tried the sample FileReader.readAsText(), but when I select the PNG image, the characters get garbled.
What should I do to prevent garbled characters?

What I want to do is to receive the PNG image data in binary format as follows and save it as it is in the database.The data is running Python on the server side, so I would like to receive it there.

b'\x89PNG\r\n\x1a\n\x00\x00\x00\...

Your OS MacOS High Sierra
The browser is chrome version 88.0.4324.150.
Thank you for your cooperation.

<!DOCTYPE html>
<html>
<head>
<style>
    div# result {white-space:pre-wrap;}
    input { width: 95%; font-size: 16px;}
</style>
</head>
<body>
    <input type="file" multiple id="hoge">
<hr>
    <divid="result"></div>
<script>
variable= document.getElementById("hoge");
var resultElement= document.getElementById("result");

element.onchange=function(){
    var fileReader = new FileReader();

    fileReader.onload=function(){
        console.log(this.result);
        resultElement.appendChild(newText(this.result);
    }

    var file=element.files[0];
    fileReader.readAsText(file);
//  fileReader.readAsBinaryString(file);// Let's try it!
}
</script>
</body>
</html>

See also

https://lab.syncer.jp/Web/API_Interface/Reference/IDL/FileReader/readAsText/

javascript html html5 image

2022-09-30 19:48

1 Answers

readAsText() is for reading text, so there is no point in using non-text PNG images.

To send a binary image file to the server, you typically include it in the form and send it as the multipart/form-data type.

*For Forms

<body>
  <form action="..." enctype="multipart/form-data">
    <input type="file" multiple id="hoge" name="files">
  </form>
<hr>
<script>
variable= document.getElementById("hoge");
element.onchange=function(){
    element.form.submit();
};
</script>
</body>

* For XHR

<body>
  <input type="file" multiple id="hoge"
<hr>
<script>
variable= document.getElementById("hoge");
element.onchange=function(){
    let fd = new FormData();
    fd.append('files', element.files[0]);
    let xhr = new XMLHttpRequest();
    xhr.open('POST', '...');
    xhr.send(fd);
};
</script>
</body>


2022-09-30 19:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.