I am new to Javascript and am working on a task to compress and then upload an already uploaded image.
I am trying to:
Retrieve the uploaded image,
Compress it
Convert it to a base64 URL
Convert it into a blob
And then into a file and upload it.
But this code just doesn't work.
When I step through it using a debugging tool it does it's job but otherwise it doesn't.
I think the rest of the code after the loadImage function call doesn't really execute.
Please help me make sense of it! Thanks!
function loadImage(formObj2, fldid2, file, callback) {
var oldImage = document.createElement("img");
var psImageOutput = new Image();
var reader = new FileReader();
reader.onload = function(e) {
/* code to compress image */
callback(psImageOutput);
}
reader.readAsDataURL(file);
}
var inputFile = fileQueue[i].file;
var formObj1 = formObject;
var fldid1 = fldid;
loadImage(formObj1, fldid1, inputFile, function(psImageOutput) {
var newImageDataSRC = psImageOutput.src;
/* Manipulate SRC string and create a blob and an image file from it */
formObj1.append(fldid1, newimgfile);
});
Be careful, on the line :
formObj1.append(fldid1, newimgfile);
You seem to append a dom node called newimgfile but in your code this variable doesn't exist.
Related
I have a current setup in React js where I upload files to s3 using multipart upload as buffer.However if the file format is pdf,video,audio etc. I want to convert it to image before uploading to s3; think of it as thumbnail generation.I have read a lot about this but could not find a right solution for my needs, can please someone suggest some possible solution?(where backend is not involved at all)
PS:I have looked at pdf.js but dont know how to use it while my file type is buffer and what type will it return and can I upload it the same way to S3.A small example would help miles. Thanks in advance !!
var pdfData = buffer;
var pdfjsLib = window['pdfjs-dist/build/pdf'];
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.min.js';
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
pdf.getPage(1).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
console.log('page',viewport);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('bulk-thumbnails');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
page.render({canvasContext: context, viewport: viewport});
});
According to the 2nd example of pdf.js (in the link below) you can also load pdf file using its base64 code.
https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples
var pdfData = atob('PDF file in Base64...');
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
});
And To load pdf file as base64 code you can actually use HTML5 FileReader like this
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);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Referenced from
How to convert file to base64 in JavaScript?
Hope it helps
I have built a functionality on the above link check this out
StackBlitz
I am developing an app which needs to record audio, and then have the audio stored as part of an object, and uploaded to a database.
I am trying to alert the base64 of the file first just to ensure it has been found correctly.
I am using the cordova media capture plugin to access the recorder on a device, and am able to record the audio, however once it has been recorded I want to convert into a base64 format before sending to the database. When I use this method it alerts the base64, but it is empty, just "data:audio/mpeg;base64," with nothing after, I do not know why it isn't converting the file correctly.
Plugin: https://github.com/apache/cordova-plugin-media-capture
function captureSuccess(capturedFiles) {
//Convert capturedFiles[0] into var containing file as base64
previewFile(capturedFiles);
alert("Audio Captured");
}
function captureError() {
alert("Audio Not Captured");
}
navigator.device.capture.captureAudio(captureSuccess, captureError, {
limit: 1,
duration: 20
});
});
/***********************************************************************************/
function previewFile(files) {
var preview = document.querySelector('img');
var file = files[0];
var reader = new FileReader();
reader.onload = function () {
alert(reader.result);
};
if (file) {
reader.readAsDataURL(file);
}
}
I was having alot of issues to this, and had looked all over StackOverFlow for an answer but had alot of trouble finding one, so for anyone in the future who has this issue I was able to solve it. The issue was that the file I wanted to convert to base64 had a "start" and an "end" which were both set the 0, so none of the bytes were being accessed. To ensure the bytes are accessed I keep the start byte as 0 (so don't change anything), and set the end byte to the same as the file size. Here is the resolved code below:
$("#btnAudio").click(function () {
function captureSuccess(capturedFiles) {
var path = capturedFiles[0].fullPath;
//Convert capturedFiles[0] into var containing file as base64
previewFile(capturedFiles);
alert("Audio Captured");
}
function captureError() {
alert("Audio Not Captured");
}
navigator.device.capture.captureAudio(captureSuccess, captureError, {
limit: 1,
duration: 20
});
});
/***********************************************************************************/
function previewFile(files) {
var file = files[0];
var reader = new FileReader();
file.end = file.size;
var preview = document.querySelector('audio');
reader.onload = function () {
/*For testing I am just alerting reader.result, but if you want to store the
base64 just create a var and set its value to reader.result*/
alert(reader.result);
};
if (file) {
reader.readAsDataURL(file);
}
}
I have a function that currently downloads multiple images and saves them to a users "download" folder (Only works in Chrome)
I want to take this function to the next step and put these images in a single zip file.
Below is an example of my current code. I want to merge my code with the JSZip API I found online here.
I have done the bower install for this JSZip API already and included the script in my html.
Here is my code that works perfectly downloading multiple SINGLE images at once:
$scope.downloadPhotos = function() {
var photoUrls = [];
for (var x = 0; x < $scope.$parent.photos.length; x++) {
var p = $scope.$parent.photos[x];
if (p.isChecked) {
photoUrls.push($scope.bucketUrl() + p.photoUrl);
}
}
saveImage(photoUrls);
};
/*----this function saveImage works great (only Chrome)-----*/
function saveImage(urls) {
var link = document.createElement('a');
link.setAttribute('download', null);
link.style.display = 'none';
document.body.appendChild(link);
for (var i = 0; i < urls.length; i++) {
link.setAttribute('href', urls[i]);
link.click();
}
document.body.removeChild(link);
}
And here is the JSZip API code example to create a zip file with content in it:
function create_zip() {
var zip = new JSZip();
zip.add("hello1.txt", "Hello First World\n");
zip.add("hello2.txt", "Hello Second World\n");
content = zip.generate();
location.href = "data:application/zip;base64," + content;
}
Now I'm just wondering how to combine the two to put my images into a zipfile.
Thanks for your help!
I put this together that will let you zip an array of image urls.
https://jsfiddle.net/jaitsujin/zrdgsjht/
You can manage zip folder structure by modifying this line
filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpsi.imgur.com","");
To Download multiple files in Zip format we can use jsZip and FileSaver.js or if we are using Web API and Angularjs then we can create an API method to create zip archieve file at server and then in angularjs we can use $http post or get api call to download the file as zip file (We have to use filesaver to save the file in zip format). for example -
api call in angularjs -
function downloadFiles(files) {
return $http.post(baseUrl + 'api/download/files', files, { responseType: 'arraybuffer' });
}
call above function and on response use fileSaver.js method saveAs to save file in zip format for example -
//files - array input of files like http://www.example.com/file1.png', 'http://www.example.com/file2.jpeg', 'http://www.example.com/file3.jpg'];
downloadFiles(files).then(function (response) {
//on success
var file = new Blob([response.data], { type: 'application/zip' });
saveAs(file, 'example.zip');
}, function (error) {
//on error
//write your code to handle error
});
You should see this example. Currently, you just ask the browser to trigger the download of a file. If you want to create a zip file client side, your js code needs to access the content of the files with ajax calls (you will get CORS issues if they aren't stored on the same server).
Without copy/pasting the whole code, the example:
triggers ajax calls (with JSZipUtils but you can easily only use a responseType = "arraybuffer" if you only supports recent browsers)
wrap them into promises (jQuery promises here but you can use your own)
add the result into a zip object
wait for all promises to complete before triggering a download
function downloadImageAsZip(imageUrl){
var zip = new JSZip();
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = imageUrl;
img.onload = function() {
$scope.count2++;
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(this, 0, 0);
ctx.enabled = false;
dataURL = canvas.toDataURL("Canvas");
canvas = null;
//var base64String = dataURL.replace("/^data:image\/(png|jpg);base64,/", "");
var base64String = dataURL.replace("data:image/png;base64,", "");
zip.file("ImageName", base64String, {base64: true});
zip.generateAsync({type:"blob"}).then(function(content) {
saveAs(content, "ZipFileName.zip");
});
}
}
I am using the javascript file api to read a file and I want to get its type out. I am mainly using it to upload audio and video files. However when i upload amr, 3gp, and aac audio files, javascript can't figure out the filetype. I need to know the filetypes for the different audio formats as I use the files differently depending on the format. Is there anyway for me to figure out the format for the above mentioned files? I have supplied the code I use below.
var f = this.files[0];
var fr = new FileReader();
fr.onload = function (ev2) {
console.dir(ev2);
//$('#image').attr('src', ev2.target.result);
//extra[extra.length] = ev2.target.result;
extra[extra.length] = ev2.target.result;
var splitted = ev2.target.result.split(','); //get the type
fileType[fileType.length] = splitted[0];
console.log("splitted[0]: "+splitted[0]);
console.log("f.type: "+f.type);
};
fr.readAsDataURL(f);
regards
Try this code:Source
Demo
JSFiddle Example
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
//onload code
}
reader.readAsText(file);
} else {
alert( "File not supported!");
}
or also this code:
var file = $("#inputFile")[0].files;
alert(file[0].type);
One of my first larger projects so please bear with me. I have a script which will help me resize an image and turn it into base64. This is how it begins:
var createImage = function (src) {
var deferred = $.Deferred();
var img = new Image();
img.onload = function() {
deferred.resolve(img);
};
img.src = src;
return deferred.promise();
};
And my question is to get the image source from the upload form to the script?
I've tried to stitch together (with help from other sources) a function with the Filereader API:
var createImageURL = function () {
var fileinput = document.getElementById('fileinput');
file = fileinput.files[0];
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function (event) {
var blob = new Blob([event.target.result]);
window.URL = window.URL || window.webkitURL;
var blobURL = window.URL.createObjectURL(blob);
}
return blobURL;
};
However this returns a GET error in the console.
Rather than going via Blob, convert your <input>'s File to an ObjectURL directly, saving yourself a lot of trouble by keeping your code synchronous and requiring fewer lines of code.
function inputToURL(inputElement) {
var file = inputElement.files[0];
return window.URL.createObjectURL(file);
}
var url = inputToURL(document.getElementById('fileinput'));
createImage(url);
This works because a File is a Blob per spec (as pointed out by Ray Nicholus)
It's not advised (as File inherits from Blob already) and highly unusual to want to convert between them, but not impossible. I'm including this so you can see how to structure FileReader code if you need it in future, not as a solution to your problem. To convert <input type="file" />'s first file to Blob, you would do
function fileToBlob(inputElement, callback) {
var fileReader = new FileReader();
fileReader.onload = function () {
callback(new Blob([this.result]));
}
fileReader.readAsArrayBuffer(inputElement.files[0]);
}
Where callback takes a Blob as it's first parameter. Remember that since the readAsArrayBuffer caused us to use a callback, we had to write this so it would work in an asynchronus environment.