Home>
Environment

Chrome 83.0.4103.116
ruby on rails 3

Target

In file upload, create a File object manually and send the data to the server with ajax

problem

[normal]
When file is uploaded in view of rails (=is directly uploaded as form) The following data is saved in the server

PNG

IHDR delete tEXtSoftwareAdobe ImageReadyqe<#iTXtXML:com.adobe.xmp
									    javascript
						    ruby
							
  • Answer # 1

    Incorrect value when using fileReader::readAsText() method

    The text will be a stream (sequence of bytes) defined by the encoding specification (character code), but if you try to read the binary file as text using readAsText(), the stream will be different from the encoding specification, so the characters will be garbled. (There were times when I was aware that this was treated as a binary-string).

    Unknown to get data like normal pattern

    MDN FileReader method

    Working with streams of binary files ...readAsArrayBuffer()

    Save as string and save in site data ...readAsDataURL()

    Reference as URL ...URL.createObjectURL()/URL.revokeObjectURL()

    PNG/APNG file format related information

    W3C PNG
    MDN Animated PNG graphics

    (Addition)

    // data to send to the server, create a file object

    From the comments in the code, about the case of POST with Ajax:

    The file object can be specified as the second argument of FormData.append().


    new File()Is also unnecessary.

    <input type="file" id="upfiles" multiple>
    <input type="button" id="checkfiles" value="confirm">
    const makePostData = () =>{
      let formData = new FormData(),
          upfiles = document.querySelector("#upfiles"),
          key = upfiles.name || upfiles.id,
          files = upfiles.files;
      for( file of files) {
        console.log( file.name, file.type );
        formData.append( key, file, file.name );
      }
    Return formData;
    }
    window.addEventListener("DOMContentLoaded", () =>{
      let btn = document.querySelector("#checkfiles");
      btn.addEventListener("click", evt =>{
        let formdata = makePostData();//User function
        // Send formdata to Ajax
      });
    });

    Addendum 2)

    I added the description about arrayBuffer as "Appendix 1" (comment column).

    Addition of question2.,3.Then, it seems that you are obsessed with making it into a binary-string,AjaxThere is also a policy to send FormData with.
    It's easy, but I think the procedure will be as follows.

    var file=new File([arraybuffer],"foo.png",{type:"image/png"});

    formData.append("upfiles", file, file.name );
    "upfiles" corresponds to the name attribute of input[type=file].

    "File upload" section of using Fetch (file upload example using FormData)