uploading files in js - javascript

i'm using below method to upload files to laravel backend
setFile(id, e) {
let self = this;
let reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onload = function () {
console.log(reader.result);
self.documentArray.forEach(function (element) {
if (id == element.id && reader.result) {
element.file = reader.result;
element.file_browse_name = e.target.files[0].name;
}
});
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
},
but when i select a file larger than 5mb or around, it doesn't add the element to the relevant object of the documentArray but it logs the result in console, so i cant add validation on backend. please give me a way to solve this problem

Maybe the problem is with your PHP settings. Check your upload_max_filesize and your post_max_size

Related

Javascript Read File + Convert to Base64 Waiting For Result Undefined

I need to convert an uploaded file into a base64, and pass it to a Web Api as a parameter.
In the examples if i write to console the reader.result it write the correct base64 result, but if i return it as a return var, i obtain an Undefined.
So i can't retrieve the result from this function, because i have to pass it to the ajax call.
How can i wait for the completation of the encoding, and get the result?
Thank u all
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
return (reader.result);
};
reader.onerror = function (error) {
return ('Error: ', error);
};
}
$(document).ready(function () {
var base64File;
var files = document.getElementById('file').files; // uploaded file
if (files.length > 0) {
base64File = getBase64(files[0]);
}
console.log(base64File) // undefined
});
The getBase64 function returns only a console log, shouldn't it return reader.result?

How to read an .AppImage from Browser

I'm trying to read an appimage from the browser's drag and drop using JS and then saving it elsewhere using node.js FS module and I've tried with all of the browsers file reader options and none of them seem to work. (they all give me a file size different than the original file)https://developer.mozilla.org/en-US/docs/Web/API/FileReader
function saveMe(readFile,filename) {
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsBinaryString(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = ()=>{};
reader.onloadend = ()=>{
//console.log(reader.readyState);
if(reader.readyState==2){
//Create File './storage/apps/'+filename, reader.result
console.log(reader.result);
fs.writeFile('./storage/apps/'+filename,reader.result,(err)=>{
if(err){
console.log("Error While reading file");
}else{
}
});
}else{
}
};
reader.onerror = ()=>{console.log("Error reading file")};
}
Which method should I use?
- FileReader.readAsArrayBuffer()
- FileReader.readAsBinaryString()
- FileReader.readAsDataURL()
- FileReader.readAsText()
Read as UTF-16 and convert it to base64 when writing, also set the write options encoding to base64
function saveMe(readFile,filename) {
var reader = new FileReader();
// Read file into memory as UTF-16
reader.readAsBinaryString(readFile, "UTF-16");
// Handle progress, success, and errors
reader.onprogress = ()=>{};
reader.onloadend = ()=>{
//console.log(reader.readyState);
if(reader.readyState==2){
//Create File './storage/apps/'+filename, reader.result
//console.log(reader.result);
fs.writeFile('./storage/apps/'+filename,window.btoa(reader.result),{encoding: "base64"},(err)=>{
if(err){
console.log("Error While reading file");
}else{
}
});
}else{
}
};
reader.onerror = ()=>{console.log("Error reading file")};
}

Read a text file and return contents

A JavaScript beginner here. I would like to write a basic function that takes a path to a local text file and returns its contents. I am aware that this question has been asked like 1000 times now, for example here. But every single answer is different from each other, I have tried a few, and they don't seem to work. After googling for a bit, I was able to come up with the following solution
function readTextFile(path) {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
var file = new File([path], { type: 'plain/text' });
reader.readAsText(file);
return contents
}
However, for some reason it outputs the path itself, not the contents. Please suggest how this code can be fixed, shortened, improved.
I also tried fetch but I get the infamous cross-origin request error, that I could not figure out how to solve easily.
EDIT:
Ok, I'll add a few more lines to make things more clear
index.html:
<input type="file" id="jsonAddressInput" value="enter address here">
script.js
function myFunction() {
var addressField = document.getElementById("jsonAddressInput");
var addressText = addressField.value;
console.log(addressText);
var textContentsOfFile = readTextFile(addressText)
//console.log(textContentsOfFile)
}
function readTextFile(path) {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
var file = new File([""], path, { type: 'plain/text' });
reader.readAsText(file);
return contents
}
It was mentioned that I can use the results of the to get file contents. Please suggest how to fix
Here's an example how to read a local file:
function readJson(blob) {
var reader = new FileReader();
reader.onload = function(event) {
contents = event.target.result;
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
var file = new File(blob, { type: 'plain/text' });
reader.readAsText(file);
}
let contents
document.querySelector("input").addEventListener("change", (e) => {
contents = readJson(e.target.files);
})
document.querySelector("button").addEventListener("click", (e) => {
console.log(contents);
})
<input type="file">
<button>show contents</button>
If you want the contents of a remote file, use fetch

JS convert PDF to base64 in local path

my project have this foldes:
-html
index.html
-css
-js
my.js
-pdf
test.pdf
I need to convert this "test.pdf" to base 64 and send by POST
I try use a function like this:
function getBase64() {
var reader = new FileReader();
var file = new File("/pdf/test.pdf","r");
reader.addEventListener("loadend", function() {
// reader.result contains the contents of blob as a typed array
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
return reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
});
But I'm not the correct way to get past the folder path, or if I have to use another object and not File.
var file = new File("/pdf/test.pdf","r");
What's the best way to do it?
Thank you!

How to create a Blob from a local file in phonegap on android

I am trying to upload a file to amazon S3 from a phonegap app on android. I already have the code working for iOS. But I've got a trouble making it work on android. The problem is that I do not know how to create the Blob object properly. On iOS I just do this:
blob = new Blob([evt.target.result], {type: "image/png"});
It is uploaded just fine. On android one can not use the Blob constructor (see here), but I could not manage to get the file data correctly into the Blob object using WebKitBlobBuilder.
Here is how I retrieve the file data, there are two approaches and both pass without errors, but the resulting file on the S3 is empty:
window.resolveLocalFileSystemURI(url, function(e){
e.file(function(f){
var reader = new FileReader();
reader.onloadend = function(evt) {
// This way also did not work:
// var builder = new WebKitBlobBuilder();
// builder.append(evt.target.result);
// blob = builder.getBlob("image/png");
var blob = null;
var builder = new WebKitBlobBuilder();
for(var i = 0; i < evt.target.result.length; i++){
builder.append(evt.target.result[i]);
}
blob = builder.getBlob("image/png");
uploadToS3(filename, s3url, blob);
};
reader.readAsArrayBuffer(f);
});
}, function(e){
console.log("error getting file");
error();
});
also, here is the uploadToS3 function:
var uploadToS3 = function(filename, s3url, fileData) {
var xhr = createCORSRequest('PUT', s3url);
if(!xhr) {
console.log('CORS not supported');
error();
return;
}
xhr.onload = function () {
if(xhr.status == 200) {
console.log('100% - Upload completed.');
callback(filename); //callback defined in outer context
}
else {
console.log('0% - Upload error: ' + xhr.status);
console.log(xhr.responseText);
error();
}
};
xhr.onerror = function () {
console.log(0, 'XHR error.');
error();
};
xhr.upload.onprogress = function (e) {
if(e.lengthComputable) {
var percentLoaded = Math.round((e.loaded / e.total) * 100);
var label = (percentLoaded == 100) ? 'Finalizing.' : 'Uploading.';
console.log(percentLoaded + "% - " + label);
}
};
xhr.setRequestHeader('Content-Type', "image/png");
//xhr.setRequestHeader('x-amz-acl', 'public-read');
xhr.send(fileData);
};
EDIT:
I checked the filesize by logging evt.target.result.byteLength and it was ok, so evt.target.result contains image data. Still there is a problem with the upload - I checked the s3 storage and file size is 0, so I am not constructing the Blob correctly.
So this is an android bug after all, which was not fixed since at least Nov 2012.
Here is an article I found which is directly related to my problem: https://ghinda.net/article/jpeg-blob-ajax-android/
It also provides a workaround for the bug, which is to send ArrayBuffer directly, without creating a Blob. In my case I had to send evt.target.result directly.

Categories