The problem is when i do no not see the form data in the console. I do not know what is wrong. here is the code:
So I got firstly the nodes and tried to create a function thta reads the file and a function that returns a src that would be stored in the readForm data function
//nodes
const mainContainer = document.getElementById("main");
const postTitleNode = document.getElementById("postTitle");
const postDateNode = document.getElementById("postDate");
const postFileNode = document.getElementById("postFile");
const postContentNode = document.getElementById("postContent");
//image file reader
function readImageFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener("load", () => {
resolve(reader.result);
});
reader.addEventListener("error", () => {
reject(reader.error);
});
reader.readAsDataURL(file);
});
}
//reading the src of the image uploaded
function readFileSrc(elementNode) {
return new Promise((resolve, reject) => {
elementNode.addEventListener("change", async () => {
const file = elementNode.files[0];
if (file.type.startsWith("image/")) {
const dataUrl = await readImageFile(file);
postFileNode.value = dataUrl;
resolve(dataUrl);
} else {
console.error("Selected file is not an image.");
reject("Selected file is not an image.");
}
});
});
}
//clear form data
function clearInputValue() {
postTitleNode.value = "";
postDateNode.value = "";
postFileNode.value = "";
postContentNode.value = "";
}
//get form Data
async function readFormData() {
//values: store the values in an object
const postFile = await readFileSrc(postFileNode);
const formData = {
title: postTitleNode.value,
postDate: postDateNode.value,
postFile: postFile,
postContent: postContentNode.value,
};
console.log(formData);
return formData;
}
//onClick function
async function onClickEvent() {
//read data
await readFormData();
//clear data after clicking
clearInputValue();
}
//buttons
const createPostButton = document.getElementById("modalCreatePostButton");
createPostButton.addEventListener("click", onClickEvent);
what can I do to solve the problem or where is my mistake? why am i not getting any data in the console
Related
i am trying to make a component that take a pdf from input or an already uploaded one and then extract pages from it and uploaded again
when choosing a file from input (choosing file from my computer)
i am using this
const handleFileChange = async (event) => {
const file = event.target.files[0];
setFiles(event.target.files[0])
const fileName = event.target.files[0].name
setFileName(fileName);
const fileReader = new FileReader();
fileReader.onload = async () => {
const pdfBytes = new Uint8Array(fileReader.result);
const pdfDoc = await PDFDocument.load(pdfBytes);
setPdfDoc(pdfDoc);
setPdfBlob(pdfBytes)
};
fileReader.readAsArrayBuffer(file);
setShowPdf(true)
};
we get a pdfDoc and a Unit8Array
then i use the pdfDoc to get pages and extract a new pdf file....
this works fine
now when selecting a file that we already uploaded
i use this to ping the api to get the file
const handleGetFile = async (url) => {
const headers = {
Authorization: "Bearer " + (localStorage.getItem("token")),
Accept: 'application/pdf'
}
await axios.put(`${process.env.NEXT_PUBLIC_API_URL}getPdfFileBlob`, {
pdfUrl: `https://handle-pdf-photos-project-through-compleated-task.s3.amazonaws.com/${url}`
}, { responseType: 'arraybuffer', headers }).then((res) => {
const handlePdf = async () => {
const uint8Array = new Uint8Array(res.data);
const pdfBlob = new Blob([uint8Array], { type: 'application/pdf' });
setPdfBlob(uint8Array)
// setPdfDoc(pdfBlob) .....? how do i create a pdf doc from the unit8array
}
handlePdf()
}).catch((err) => {
console.log(err)
})
}
this the the end point i am pinging
app.put('/getPdfFileBlob',async function(req,res){
try {
console.log(req.body.pdfUrl)
const url =req.body.pdfUrl;
const fileName = 'file.pdf';
const file = fs.createWriteStream(fileName);
https.get(url, (response) => {
response.pipe(file);
file.on('finish', () => {
file.close();
// Serve the file as a response
const pdf = fs.readFileSync(fileName);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader( 'Content-Transfer-Encoding', 'Binary'
);
res.setHeader('Content-Disposition', 'inline; filename="' + fileName + '"');
res.send(pdf);
});
});
} catch (error) {
res.status(500).json({success:false,msg:"server side err"})
}
})
after getting this file here is what am trying to do
const handlePageSelection = (index) => {
setSelectedPages(prevSelectedPages => {
const newSelectedPages = [...prevSelectedPages];
const pageIndex = newSelectedPages.indexOf(index);
if (pageIndex === -1) {
newSelectedPages.push(index);
} else {
newSelectedPages.splice(pageIndex, 1);
}
return newSelectedPages;
});
};
const handleExtractPages = async () => {
for (let i = pdfDoc.getPageCount() - 1; i >= 0; i -= 1) {
if (!selectedPages.includes(i + 1)) {
pdfDoc.removePage(i);
}
}
await pdfDoc.save();
};
well in the first case where i upload the pdf file from local storage i get a pdfDoc
console of pdf Doc and pdfBlob
and when i select already existing file i can't find a way to transfer unit8array buffer to pdf doc
log of pdfBlob and no pdf doc
what i want is transform the pdfblob to pdfDcoument or get the pdf document from the array buffer so i can use getpages on it
When I run tesseract.js on a URL it works fine. But when I run it on a local file I get these errors. How can I solve this?
I am running tesseract.js v2.1.0 and here is my code:
const { createWorker } = require('tesseract.js');
const worker = createWorker({
logger: m => console.log(m), // Add logger here
});
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize('download.png');
console.log(text);
await worker.terminate();
})();
If you want to load local images in tesseract you have to load them via input tag, Here is the working example.
HTML
<input type="file" id="input_image" accept="image/*">
JavaScript
const input_image = document.getElementById("input_image");
const offscreen_canvas = new OffscreenCanvas(0, 0);
const offscreen_canvas_context = offscreen_canvas.getContext("2d");
input_image.addEventListener("change", () => {
var file = input_image.files[0];
if (file == undefined) return;
var reader = new FileReader();
reader.onload = function (event) {
const reader_image = event.target.result;
const image = new Image();
image.onload = function () {
offscreen_canvas.width = image.width;
offscreen_canvas.height = image.height;
offscreen_canvas_context.drawImage(image, 0, 0);
offscreen_canvas.convertToBlob().then((blob) => {
Tesseract.recognize(blob, "eng", {
logger: (m) => console.log(m)
}).then(({ data: { text } }) => {
console.log(text);
});
});
};
image.src = reader_image;
};
reader.readAsDataURL(file);
});
I need to store one image and text in clipboard. I'd like to use Clipboard API. Is it possible?
I'm using following sample to store Image or Text but is it possible to combine?
copyImgBtn.addEventListener('click', async () => {
const response = await fetch(img.src)
const blob = await response.blob()
const blob1 = new Blob([textarea.value], { type: 'text/plain' })
var data = [new ClipboardItem({[blob.type] : blob})]
navigator.clipboard.write(data).then(function() {
console.log("Copied to clipboard successfully!");
}, function() {
console.error("Unable to write to clipboard. :-(");
})
}
)
Thank you
As you cannot write multiple ClipBoardItems at once, I used a single text/html blob.
(Note that the below snippet will not run here, because of browser permissions policy)
I found the blobToBase64 function here: https://stackoverflow.com/a/18650249/91017
Hope this helps,
Koen
async function copyToClipboard() {
const imageUrl = 'https://i.picsum.photos/id/739/200/300.jpg?hmac=xApsFbHx511SUVG612QiltrATotVTYu3Q4wfvGyYC1g';
try {
const imageData = await fetch(imageUrl);
const imageBlob = await imageData.blob();
const imageBase64Data = await blobToBase64(imageBlob);
const html =
`<p>Some text</p>
<p><img src="${imageBase64Data}" alt="Some image"></p>`;
const textBlob = new Blob([html], {
type: 'text/html'
});
await navigator.clipboard.write([
new ClipboardItem({
[textBlob.type]: textBlob
})
]);
console.log('Copied.');
} catch (err) {
console.error(err.name, err.message);
}
}
function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
<button onclick="copyToClipboard()">Copy text and image to clipboard</button>
I have an upload in my application, which receives an encrypted file. When doing the decryption I'm writing json in another file. After completing this operation I have a 500MB json file.
Note: The properties of my json are dynamic.
How can I parse this json, I read about stream-json/Parser but could not implement it.
const {parser} = require('stream-json/Parser');
static async _recoverObj(pathAnalise) {
let readStream = fs.createReadStream(pathAnalise, {encoding: 'utf8', highWaterMark: 1024});
function createJson(stream) {
let decipher = crypto.createDecipher('aes-128-ecb', 'AmbientalRuralBR');
return new Promise((resolve) => {
stream.on('data', chunk => {
let newDecrypt = decipher.update(chunk, 'base64', 'utf8');
fs.appendFile('./data.json', newDecrypt, function() {
console.log('Saved!');
});
});
stream.on('end', () => {
fs.appendFile('./data.json', '"}', function() {
resolve();
});
});
});
}
const result = await createJson(readStream);
function getParse() {
return new Promise((resolve) => {
let jsonData = './data.json';
let pipeline = fs.createReadStream(jsonData).pipe(parser());
let objectCounter = 0;
pipeline.on('data', data => {
data.name === 'startObject' && ++objectCounter
});
pipeline.on('end', () => {
console.log(`Found ${objectCounter} objects.`);
resolve();
});
});
}
let dataAnalyze = await getParse();
return dataAnalyze;
}
Anyone have any idea how to do this parse?
MY SOLUTION:
I used https://www.npmjs.com/package/big-json
const json = require('big-json');
static async _recoverObj(pathAnalise) {
var readStream = fs.createReadStream(pathAnalise, {encoding: 'utf8', highWaterMark: 1024 * 2});
function createJson(stream) {
var decipher = crypto.createDecipher('aes-128-ecb', 'AmbientalRuralBR');
return new Promise((resolve) => {
stream.on('data', chunk => {
var newDecrypt = decipher.update(chunk, 'base64', 'utf8');
fs.appendFile('./data.json', newDecrypt, function() {
console.log('Saved!');
});
});
stream.on('end', () => {
fs.appendFile('./data.json', '"}', function() {
resolve();
});
});
});
}
await streamToString(readStream);
function getParse() {
return new Promise((resolve) => {
var jsonData = './max.json';
var myObj = [];
const readStream = fs.createReadStream(jsonData);
const parseStream = json.createParseStream();
parseStream.on('data', function(pojo) {
myObj = pojo;
});
parseStream.on('end', function() {
resolve(myObj);
});
readStream.pipe(parseStream);
});
}
let dataAnalyze = await getParse();
return dataAnalyze;
}
Once you have the text string containing your json you can use JSON.parse() in order to translate it to an object that you can later interact with :
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
I am trying to load a xlsx file by clicking a button without using input . The file "seedFile" is inside my project structure .The logic ran correct when I used a input but for internal files I am facing this issue and getting an err.
var excelToJson =function (file) {
return new Promise(function (resolve, reject) {
var xlData = {};
var reader = new FileReader();
reader.readAsBinaryString(seedFile);
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function (sheetName) {
xlData[sheetName] =
XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
})
};
reader.onprogress = function (data) {
if (data.lengthComputable) {
var progress = parseInt(((data.loaded / data.total) * 100), 10);
console.log(progress);
}
}
reader.onerror = function (ex) {
reject(ex);
};
reader.onloadend = function () {
resolve(xlData)
}
})
}
var handleFiles = function (files) {
var file = seedFile
return excelToJson(file)
}
$("#seedFile").click(async () => {
handleFiles(this.files).then(function success(data) {
console.log(data);
grid.setData(data.Sheet1).getInstance().loadData()
}, function error(err) {
alerts.error(err);
})
})
TypeError: Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'. Is there any easy way to make the file as a blob internally ?