Download file converted from Blob - javascript

In Javascript, test browser is Firefox. I have converted files to an array of bytes to store on my server and have used the subsequent code to convert the bytes back to a file, but I am unsure as to how to download the newly created file with appropriate file type can anyone please direct me?
to blob
$('input[type="file"]').change(function(e){
function convertFile(file){
return Array.prototype.map.call(new Uint8Array(file), x => ('00' + x.toString(16)).slice(-2)).join('');
}
file = event.target.files[0];
fileName = file.name;
fileSplit = fileName.split('.');
last = fileSplit.length-1;
let fileType = fileSplit[last];
$('#FileNameVisible').text(fileName);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
fileData = e.target.result;
fileData = convertFile(e.target.result);
console.log(fileData);
};
reader.onerror = function() {
console.log(reader.error);
};
});
from Blob
var file = new File([dataUse], "File", {lastModified: Date.now()});
console.log(file);

Related

JSZip corrupts pdf and jpeg files

Here is a very simple example of zipping file with JSZip (codepen example)
let fileInput;
document.addEventListener("DOMContentLoaded", async function () {
fileInput = document.getElementById("file");
});
function zip() {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = async function (e) {
const zip = new JSZip();
zip.file(file.name, e.target.result);
const content = await zip.generateAsync({
type: "base64"
});
createDownloadLink(content, "signed.zip");
};
reader.onerror = function (e) {
console.log("Error : " + e.type);
};
reader.readAsBinaryString(file);
}
function createDownloadLink(content, fileName) {
var link = document.getElementById("downloadLink");
if (link) {
link.remove();
}
link = document.createElement("a");
link.innerHTML = "Download zip";
link.setAttribute("href", "data:application/zip;base64," + content);
link.setAttribute("download", fileName);
link.setAttribute("id", "downloadLink");
document.getElementById("downloadLinkPanel").appendChild(link)
}
If we use text file, everythig works fine.
If we use a pdf or jpeg file, then it breaks in the archive and cannot be opened by applications
You shouldn't use readAsBinaryString, use readAsArrayBuffer instead (according to this post on Github, readAsBinaryString will convert the binary data to a UTF-16 string, which isn't what you want; by using readAsArrayBuffer, you'll get the raw bytes of the file).

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)

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);
}

file reader read blob file

i am trying to use filereader to access a blob file located locally, such as c drive, then converts it back to object URL as img src. it is not working, can anyone help this?
never found anyone try to access a blob file from disk. what is the blob file type extension?
const imageOut = document.querySelector('#image-out');
imageOut.addEventListener('load', () => {
const reader = new FileReader();
reader.addEventListener('load', () => {
var f = File.createFromFileName("file:///C:/blob.blb");
const arrayBuffer = reader.readAsArrayBuffer(f);
const blob = new Blob([arrayBuffer], { type: mimeType });
imageOut.src = URL.createObjectURL(blob);
});
});
empty, not show
Check how to use blob here it is clearly explained and it should be enough to get you going.
Try this:
Assuming that file:///C:/blob.blb exists and you are sure, then do it like so:
imageOut.addEventListener('load', () => {
const reader = new FileReader();
var f = File.createFromFileName("file:///C:/blob.blb");
reader.addEventListener('load', (e) => {
const arrayBuffer = reader.readAsArrayBuffer(f);
global.blob = new Blob([arrayBuffer], { type: f.type});
});
// notice this is outside the reader Load.
var intval = setInterval(function(){
if(blob !== undefined){
imageOut.src = URL.createObjectURL(blob);
clearInterval(intval);
}
}, 100);
});
I hope it helps.

Firebase Storage: "Invalid argument in put at index 0: Expected Blob or File

I keep getting an Invalid argument in put at index 0: Expected Blob or File error. The funny thing is the argument is totally a file...
Here is the code:
var file = document.getElementById('cke_69_fileInput')
.contentWindow.document.getElementById('cke_69_fileInput_input').files[0];
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(file);
Here's the screenshot of the actual file warn just before the error asking for a file...
try converting file to blob...
var reader = new FileReader();
reader.onloadend = function (evt) {
var blob = new Blob([evt.target.result], { type: "image/jpeg" });
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(blob);
}
reader.onerror = function (e) {
console.log("Failed file read: " + e.toString());
};
reader.readAsArrayBuffer(file);

Categories

Resources