Reactjs - Can't base64 encode file from react-dropzone - javascript

I am using react-dropzone to handle file upload on my website. When successfully loading a file, the dropzone triggers the following callback:
onDrop: function (acceptedFiles, rejectedFiles) {
myFile = acceptedFiles[0];
console.log('Accepted files: ', myFile);
}
I would like to base64 encode this file. When doing :
var base64data = Base64.encode(myFile)
console.log("base64 data: ", base64data) // => base64 data: W29iamVjdCBGaWxlXQ==W29iamVjdCBGaWxlXQ==
Regardless of file uploaded, it always prints out the same string.
Am I missing something ? I need to base64 encode this file (always images)

This JS Bin is a working example of converting a File to base64: http://jsbin.com/piqiqecuxo/1/edit?js,console,output . The main addition seems to be reading the file using a FileReader, where FileReader.readAsDataURL() returns a base64 encoded string
document.getElementById('button').addEventListener('click', function() {
var files = document.getElementById('file').files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}

If you want it in a neat method that works with async / await, you can do it this way
const getBase64 = async (file: Blob): Promise<string | undefined> => {
var reader = new FileReader();
reader.readAsDataURL(file as Blob);
return new Promise((reslove, reject) => {
reader.onload = () => reslove(reader.result as any);
reader.onerror = (error) => reject(error);
})
}

Related

How can I send an image represented as base64 encoding to a Python server using ReactJS? [duplicate]

This question already has answers here:
ReactJS base64 file upload
(2 answers)
Closed 2 months ago.
React js antd upload component send image base64 to the python server
Image upload send to the server base64
Without using formData method
Try this one
Please refer antd doc for uploading.
https://ant.design/components/upload
handleChange= (info: any) => {
let fileList = [...info.fileList];
fileList.forEach(function (file, index) {
let reader = new FileReader();
reader.onload = (e) => {
file.base64 = e.target.result;
};
reader.readAsDataURL(file.originFileObj);
});
this.setState({ fileList });
};
You need input type="file" to select an image:
<input
type="file"
onChange={onChange}
/>
Function to convert file to base64:
const convertBase64 = (file) => new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.readAsDataURL(file)
fileReader.onload = () => {
resolve(fileReader.result)
}
fileReader.onerror = (error) => {
reject(error)
}
})
And onChange handler:
const onChange = async event => {
const file = event.target.files[0]
const base64 = await convertBase64(file)
const formData = new FormData()
formData.append('file-key', base64)
// --- now you can send base64 file to server --- //
await fetch('api/{your-api-here}', {
method: 'POST',
body: formData,
})
}

readAsDataUrl converting to octet-stream instead of pdf

I am getting a blob data from a RESTFul endpoint and then I need to convert it to base64 string with file type as application/pdf however its converting it to application/octet-stream.
Here's what my codes does:
const getBytesData = () => {
if (user) {
getInvoicePDFStringByInvoiceId('129', user.user.token).then((data) => {
if (data.blob) {
const reader = new FileReader();
reader.readAsDataURL(data.blob);
reader.onloadend = () => {
var base64data = reader.result.replace('octet-stream', 'pdf');
console.log('Pdf loaded:- ', base64data);
setPDFLoaded(base64data);
return;
};
} else {
console.log('Error happened from API = ', data.error, data.message);
}
});
}
};
Can someone help me understand what could solve this issue?

Moodle corrupted uploaded files

I am using moodle api core_files_upload with node js using this script
const { CallService } = require("../MoodleWS")
var Upload = async function(userid, file) {
var base64 = await toBase64(file)
.then(r => {
return r;
})
.catch((e) => {
console.log(e)
});
console.log(base64);
var param = {
itemid: 0,
instanceid: userid,
filearea: 'draft',
filecontent: base64,
component: 'user',
filepath: '/',
filename: file.name,
contextlevel: 'user'
}
// return promise calling web service, basically returned axios
return CallService('POST', 'core_files_upload', false, null, param);
}
const toBase64 = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
})
module.exports = { Upload }
the function returned success and files uploaded, I have checked the uploaded file size is the same as the original files, unfortunately I failed to open the files and keeps saying like image below
and images also can't be displayed
the uploaded base64 also have the mime/type header like data:application/pdf;base64,JVBERi0xLjQNJeL... I don't really know what went wrong. When I tried to upload files using the native web version of moodle, the files uploaded correctly. So anyone can help? Thanks
So it turned out that I don't need to include the mime/type from the base64. So I just remove the data:application/pdf;base64 and modify my param a little so it became like
var base64 = await toBase64(file)
.then(r => {
return r;
})
.catch((e) => {
console.log(e)
});
var param = {
itemid: 0,
instanceid: userid,
filearea: 'draft',
filecontent: base64.split(',')[1],
component: 'user',
filepath: '/',
filename: file.name,
contextlevel: 'user'
}

Is it possible to convert a blob file into a base64Data in Javascript (Ionic,Angular)?

[
async FileZip() {
const code = await fetch("./assets/input.txt")
var blob = await downloadZip([code]).blob()
console.log(blob);
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
FileSharer.share({
filename: "input.zip",
base64Data: //base64datawillbehere ,
contentType: 'application/zip'
});
reader.readAsDataURL(blob);
})
I am pretty new to Ionic and App Development.
I have compressed a text file into a zip blob file using client-zip library. Using the downloadZip() I am getting a zip blob file like this.
I want to share this file as a zip file using Capacitor Filesharer . But to use this Filesharer plugin , it seems I have to convert this blob zip file into base64 data.
Can anyone tell how to do it ?? Or is it even possible to do this ??
Please forgive me If you find my question too immature ,because as I said I am pretty new to javascript .
Consider using the following function:
function blobToBase64(blob: Blob): Observable<string> {
return new Observable<string>(observer => {
const reader = new FileReader();
reader.onerror = observer.error;
reader.onabort = observer.error;
reader.onload = () => observer.next(reader.result as string);
reader.onloadend = observer.complete;
reader.readAsDataURL(blob);
})
}
Try modifying your code as demonstrated below: (haven't changed the previous answer as it might be useful for others to implement such operations using Observable strategy unlike your case where I would recommend of using Promise)
ngOnInit(): void {
this.fileZip();
}
private blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onabort = reject;
reader.onload = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
})
}
private async fileZip(): Promise<void> {
const code = await fetch("./assets/input.txt")
const blob = await downloadZip([code]).blob();
const base64Data = await this.blobToBase64(blob);
await FileSharer.share({
filename: "input.zip",
base64Data: base64Data,
contentType: "application/zip",
})
}
You can try this code -
fileZip() {
constcode = awaitfetch("./assets/input.txt");
varblob = awaitdownloadZip([code]).blob()
console.log(blob);
varreader = newFileReader();
reader.readAsDataURL(blob);
reader.onloadend = ()=> {
constresult = reader.resultasstring;
constbase64Data = result.split(',')[1];
console.log(base64Data)
FileSharer.share({
filename:"json.zip",
base64Data,
contentType:'application/zip'
});
}
}

Pako not able to deflate gzip files generated in python

I'm generating gzip files from python using the following code: (using python 3)
file = gzip.open('output.json.gzip', 'wb')
dataToWrite = json.dumps(data).encode('utf-8')
file.write(dataToWrite)
file.close()
However, I'm trying to read this file now in Javascript using the Pako library (I'm using Angular 2):
this.http.get("output.json.gzip")
.map((res:Response) => {
var resText:any = new Uint8Array(res.arrayBuffer());
var result = "";
try {
result = pako.inflate(resText, {"to": "string"});
} catch (err) {
console.log("Error " + err);
}
return result;
});
But I'm getting this error in the console: unknown compression method. Should I be doing something else to properly inflate gzip files?
Turns out that I needed to use the res.blob() function to get the true binary data, not res.arrayBuffer(); and then convert the blob to the array buffer:
return this.http.get("output.json.gzip", new RequestOptions({ responseType: ResponseContentType.Blob }))
.map((res:Response) => {
var blob = res.blob();
var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function() {
arrayBuffer = this.result;
try {
let result:any = pako.ungzip(new Uint8Array(arrayBuffer), {"to": "string"});
let obj = JSON.parse(result);
console.log(obj);
} catch (err) {
console.log("Error " + err);
}
};
fileReader.readAsArrayBuffer(blob);
return "abc";
});

Categories