React redux read .txt file - javascript

I am using React and Redux together.
I have an action file called UploadFileAction.js and here is the code:
export const selectFile = (file) => {
return {
type: 'FILE_SELECTED',
payload: file
}
};
The file parameter contain the uploaded file.
What I want to do
I want to send the file content to my reducer not the whole file as a payload..
What I have tried
let fileReader = new FileReader();
fileReader.readAsText(file, "UTF-8");
fileReader.onload = function(fileLoadedEvent){
let textFromFileLoaded = fileLoadedEvent.target.result;
}
Now the textFromFileLoaded variable contain my file text but I couldn't pass it in my payload.

Maybe I am misunderstanding, but you have to dispatch the result of the action containing the file's text to pass it to the reducer. So it should look something like:
let fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
dispatch(selectFile(fileLoadedEvent.target.result));
}
fileReader.readAsText(file, "UTF-8");
further reading on this topic: https://redux.js.org/docs/basics/Actions.html

Related

How would I convert an image to base64 in reactJS

I have this function where I call a function and have a local file as the parameter to convert it to base64.
export const fileToBase64 = (filename, filepath) => {
return new Promise(resolve => {
var file = new File([filename], filepath);
var reader = new FileReader();
// Read file content on file loaded event
reader.onload = function(event) {
resolve(event.target.result);
};
// Convert data to base64
reader.readAsDataURL(file);
});
}
Importing the function
fileToBase64("shield.png", "./form").then(result => {
console.log(result);
console.log("here");
});
gives me an output as
data:application/octet-stream;base64,c2hpZWxkLnBuZw==
here
I want base64 information, but noticing the file the application/octet-stream is wrong? I entered an image so shouldn't it be
data:image/pgn;base64,c2hpZWxkLnBuZw==
https://medium.com/#simmibadhan/converting-file-to-base64-on-javascript-client-side-b2dfdfed75f6
try this I think this should helpfull
let buff = new Buffer(result, 'base64');
let text = buff.toString('ascii');
console.log(text)

Convert buffer to file [FileCollection:meteor/ostrio:files]

when i get the image from the input
i have to convert it to a buffer to make some operations with the image, so as a result a i have a buffer instead of file.
im using FileCollection in meteor to store the image in mongo collection
uploadIt(e) {
e.preventDefault();
var reader = new FileReader();
var buffer;
var file = e.currentTarget.files[0];
if (e.currentTarget.files && e.currentTarget.files[0]) {
reader.onload = function(e){
buffer = new Uint8Array(reader.result);
// some operations over the buffer
};
reader.readAsArrayBuffer(file);
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: buffer,
..
..
})
}
}
but when i insert it got this error
message: "[FilesCollection] [insert] Have you forget to pass a File itself?
the code originally was
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: file,
..
..
})
}
but since i had to perfom operations over the the image i need to someway conver the buffer to file
any ideas how to solve this ?
Short answer
use the file constructor to turn bits back to a file container:
file: new File([buffer], file.name, file)
you could try using blob also with wider browser support... but if you want to use the latest tech, then:
async uploadIt (evt) {
evt.preventDefault()
const file = evt.currentTarget.files[0]
if (!file) return
const buffer = new Uint8Array(await file.arrayBuffer())
// some operations over the buffer
const uploadInstance = CourseFilesCollection.insert({
file: new File([buffer], file.name, file)
})
}

Uncaught DOMException: Failed to execute 'readAsDataURL' on 'FileReader'

I have been task to create and upload image file but i am having issue with the blob and base64 items the Blob URL is working as expected but when i try to use a FileReader it is showing the item is busy reading blob. I have also tried to remove the code files for URL the retain the File Reader code but still same issues. And also how the onload is called every time how to stop it after the base64 is created. Or is it also posible to convert the blob URL to a base64
uploadImageChange(e){
const file = e.target.files[0];
this.showImageModalErrorMessage = false;
let fileReader = new FileReader();
fileReader.onload = function(fileLoad){
console.log(fileReader.readAsDataURL(file));
}
if(file.size < 2000){
this.imageSelectedUrl = URL.createObjectURL(file);
this.showImageSaveContent = true;
this.modalSecondInstruction = true;
}else{
this.imageModalErrorMessage = "The image you chose is bigger than 2 MB. Kindly upload a smaller-sized photo."
this.showImageModalErrorMessage = true;
}
},
Try this way
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(fileLoad){
consoloe.log(fileReader.result);
}
Had a similar problem, the below code worked for me fine.
fileReader(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const blobFile = new Blob([reader.result], { type: file.type });
formData.append("file", blobFile, "filename");
// POST formData call
};
reader.readAsArrayBuffer(file);
}

How can i read data from blob url?

I have to read the data as an array of characters or even better as an base64 string from a blob url,
for later processing.
The blobUrl that i have to read for example is
blob:https://localhost:44399/a4775972-6cc8-41a3-af64-1180d9941ab0
Actually when following the link, the file is previewed in my browser.
While trying to read the file
var blobUrl = document.getElementById("test").value;
var reader = new FileReader();
reader.readAsDataURL(blobUrl);
reader.onloadend = function ()
{
base64data = reader.result;
console.log(base64data);
}
I get the error
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
What am i doing wrong here?
readAsDataURL does not actually accept url as input?
How can i fix that?
As spec says, readAsDataURL accept Blob only (which is File inheritor) as a param.
So you need to use original blob file reference (if you have it) or convert URL into file instance.
To convert image URL into the file itself, you can do the following.
async function convertToFile(url){
let response = await fetch(url);
let blob = await response.blob();
return new File([blob], 'put_the_name.jpg', {
type: 'image/jpeg'
});
}
// usage
async function main() {
const url = document.getElementById("test").value; // get file URL somehow
const file = await convertToFile(url); // usage of function above
const reader = new FileReader();
reader.readAsDataURL(file);
...
}
Or if you have an input in your markup for uploading files (which is popular use case), you can get file reference directly.
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}

Give a bits parameter of the File object using Ionic 3 file url

I have this base64 conversion method. It expects file and type as Blob. But I have file path for the pdf file. e.g.: let filePath: string = 'file:///...my.pdf';. So how can I consume below method then?
getBase64(file: Blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
I have seen this solution. But it expects more than what the dev mentioned.
i.e. new File("/path/to/file");. This is simpley not work. It expects like this File(bits, name [, options]);. But how can I give bits part?
I don't need the above method since native file plugin does the job for me.i.e. it returns the base64 string.
let base64String = await this.file.readAsDataURL(pdfFilePath, pdfFilename)

Categories

Resources