1

I´m using the react library: https://react-jsonschema-form.readthedocs.io/en/latest/ to create forms form a json file, and to upload local files.

I'm using the "files" example form the live demo to load a local file

Which the library is doing sucessfuly. I have verified this because I create a text file which content is the string "test" and when I load the file

enter image description here

In the chrome console I get the following response:

{schema: {…}, uiSchema: {…}, idSchema: {…}, formData: {…}, edit: false, …}
additionalMetaSchemas: undefined
edit: false
errorSchema: {}
errors: []
formData: {file: "data:text/plain;name=Nuevo%20documento%20de%20texto.txt;base64,dGVzdA=="}
idSchema: {$id: "root", file: {…}}
schema: {title: "Files", type: "object", properties: {…}}
uiSchema: {}
__proto__: Object

All the details of the file, like its name and content are in the variable formData E.G. the content "dGVzdA==" once encoded is "test" which means tha it does read the file.

formData: {file: "data:text/plain;name=Nuevo%20documento%20de%20texto.txt;base64,dGVzdA=="}

My problem is that I'm unable to access the data from there, I have tried typing:

FormData

Which gives me the result:

ƒ FormData() { [native code] } 

But nothing else. I have also tried with

FormData["file"] and "file" but none of those work

I have also tried with:

document.getElementById("root");

But that only gives me the html code, not the content of the file I have uploaded.

intekhab
  • 1,566
  • 1
  • 13
  • 19
Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

1 Answers1

1

A very simple way to do it is using the fetch api:

fetch(formData)
    .then(res => res.blob())
    .then(blob => blob.text())
    .then(console.log)

The only problem though is that it can violate the Content Security Policy (CSP).

If that's your case, you can use a custom function to parse the dataURL and use it like this:

function dataURItoBlob(dataURI) {
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer
    var ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done
    var blob = new Blob([ab], {type: mimeString});
    return blob;
}

dataURItoBlob(formData).text().then(console.log)
Carlos Jiménez
  • 486
  • 2
  • 8