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
Related
I am trying to send an image to my express backend. I have tried adding the image directly to my post request body.
var imgValue = document.getElementById("image").value;
In my post request
body : JSON.stringify({
image:imgValue
})
Accessing the image on the backend only gives me the name of the file. Is there any way I can encode the image as a base64 string in the frontend itself?
You need to load the image into a temporary img element and then you can convert it to base64 when the temporary element has loaded the image.
Use the image as img.src = (YourImageSource)
From the onload function you can then retrieve the base64 value.
var imgEl = document.createElement('img');
imgEl.onload = function(){
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(this,0,0);
const d = canvas.toDataURL('image/jpeg');
console.log('base64',d);
};
imgEl.src = img;
Run below code, if you already upload your file then the console will show the base64 of the file
The example is for only first file.
If you need upload more than one files. You can loop to make it.
document.getElementById("image").files;
Using files array to get each file's base64.
var file = document.getElementById("image").files[0];
var reader = new FileReader();
reader.onload = function (r) {
var fileInfo = new Object();
fileInfo.name = file.name;
fileInfo.size = file.size;
fileInfo.extension = file.name.split(".")[file.name.split(".").length - 1];
console.log(r.target.result.split("base64,")[1]);
};
reader.onerror = function (ex) {
console.error(ex);
};
reader.readAsDataURL(file);
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.
I use Microsoft Azure Blob Storage to stored my video.
How do I generate the thumbnail from the video's url that I get from backend using ajax.
axios.post('my-api')
.then(function(response) {
var videoUrl = response.data.url;
// How to generate thumbnail here
})
#Gary, I'd recommend checking this thread which may of help to your question. using the following tutorial
They used the following code:
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
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");
});
}
}