I want to create a new blob in memory, put the content in the blob, name it, and finally save it as a file in Drive.
I know how to create a file in Drive from blobs. The only thing I'm looking for is creating the empty new blob to start with.
You can create a new blob in memory with the Utilities Service:
function createNewBlob() {
var blobNew = Utilities.newBlob("initial data");
blobNew.setName("BlobTest");
Logger.log(blobNew.getName());
blobNew.setDataFromString("Some new Content");
Logger.log(blobNew.getDataAsString())
var newFileReference = DriveApp.createFile(blobNew);
newFileReference.setName('New Blob Test');
};
You can also create a new file, with some small amount of data, then change the content. In this example, a file is created in the root directory with the contents "abc". Then the content of the blob is set to something else.
function createNewBlob() {
// Create an BLOB file with the content "abc"
var blobNew = DriveApp.createFile('BlobTest', 'abc', MimeType.Blob);
Logger.log(blobNew.getName());
blobNew.setContent("Some new Content");
Logger.log(blobNew.getBlob().getDataAsString())
};
You could create data in memory, then create the blob with the finished data.
Related
I am using the package hopding/pdf-lib from github within the browser to generate a pdf. I get the result as a uint8array. I can send this to the browser using rndme/download from github which stores the pdf first to the local disk and then sends it to a new browser tab and opens it in the pdf viewer. As I dont want to store it to disk i tried the following code:
const pdfBytes = await pdfDoc.save(); // create the pdf as uint8array
//download(pdfBytes, fn, "application/pdf");
let blb = new Blob(pdfBytes, {type: 'application/pdf'});
let link = window.URL.createObjectURL(blb);
window.open(link);
This opens the new tab with the pdf viewer, however it is empty. I checked the blob with the debugger and it tells me:
Blob { size: 772729, type: "application/pdf" }
There are no error messages. Why is the target empty?
The pdfBytes should be passed into the blob constructor in an array. The first argument of the blob constructor should be an array containing all the objects to be inserted into the blob.
An error is not being thrown because pdfBytes is an array of numbers, so all the numbers in the array are being inserted into the blob, rather than pdfBytes itself.
The blob creation should look like this:
let blb = new Blob([ pdfBytes ], {type: 'application/pdf'})
// notice how pdfBytes is passed inside of an array
Brilliant!! That's working. Thanks alot!
I am using a code editor and a file view, I want whatever the user type in the code editor auto saves in the file. I have a function to download the file with the current text inside like this:
function saveFile() {
var text = editor.doc.getValue();
var text = text.replace(/\n/g, "\r\n");
var blob = new Blob([text], {type: "text/x-python;charset=utf-8"});
saveAs(blob, selectedFileName.name);
}
using a FileSaver.js, link: http://purl.eligrey.com/github/FileSaver.js.
I store the files in a file array and display them as unordered list.
Currently I am replacing the whole file like this:
fileList[0] = new File(["content"], "filename");
Can I update the text of a file in the fileList directly, without the need of creating a new file and replacing it?
You can use local sotage for store data at client side.
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
How do you view a blob data that is from a sql database file (.db .db3 and others) and view it on web browser by only using a single html file? The blob data are probably meant to be seen as an image file (jpg, png and others)
Let's say I have a blob data like this:
du�� C�BVwv�q8q7k�1�H�asfdasdfasdf�#s;47sk"as��'7hib-�3$asdffdsfa�a�����U�����P������
And I want to put that single blob data directly (without calling the database file, just using the value of the blob itself) inside a html file so I can directly open it from my browser without installing other software or setting up a local server inside my computer.
I'm sorry if I explain this weirdly, I rarely code, I honestly don't know anything about sql or that server thingamajig, I just want to view the blob file.
You could use Blob. Here I construct a blob and then turn it back into a string that I insert in the document.body.
var array = ['<p>Hello World!</p>'];
var blob = new Blob(array, {type : 'text/html'});
const reader = new FileReader();
reader.addEventListener('loadend', e => {
document.body.innerHTML += e.target.result;
});
reader.readAsText(blob);
And I guess that the Filereader can also read a file if needed.
I want to convert a blob file to a png. I tried this:
var blob = new Blob([ia], {type: 'image/png'});
$scope.farmerRegisterObj.farmerImage = blob;
I want to convert it into file object ..and should be able to append in a Formdata.
A Blob is a File like object, or more exactly, a File object is a Blob with a name property.
You can create a File object from a Blob thanks to the File(blob, name) constructor, but this will be useless in almost every use cases*.
All you can do with a File can be done with a Blob.
For instance, in your case, you can append a Blob directly into a FormData so that it is sent as a file/multipart :
var form = new FormData();
form.append(fieldName, blob, fileName);
* I only used it once, while trying to hack the behavior of browsers default page title when viewing a file like an image in a tab, and it only partially worked only in FF. If someone has real use cases where a File is needed, I'd be glad to know about it.
I have an HTML5/javscript app which uses
<input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)">
to capture a camera image. Because my app wants to be runnable offline, how do I save the File (https://developer.mozilla.org/en-US/docs/Web/API/File) object in local storage, such that it can be retrieved later for an ajax upload?
I'm grabbing the file object from the using ...
function gotPhoto(element) {
var file = element.files[0];
//I want to save 'file' to local storage here :-(
}
I can Stringify the object and save it, but when I restore it, it is no longer recognised as a File object, and thus can't be used to grab the file content.
I have a feeling it can't be done, but am open to suggestions.
FWIW My workaround is to read the file contents at store time and save the full contents to local storage. This works, but quickly consumes local storage since each file is a 1MB plus photograph.
You cannot serialize file API object.
Not that it helps with the specific problem, but ...
Although I haven't used this, if you look at the article it seems that there are ways (although not supported yet by most browsers) to store the offline image data to some files so as to restore them afterward when the user is online (and not to use localStorage)
Convert it to base64 and then save it.
function gotPhoto(element) {
var file = element.files[0];
var reader = new FileReader()
reader.onload = function(base64) {
localStorage["file"] = base64;
}
reader.readAsDataURL(file);
}
// Saved to localstorage
function getPhoto() {
var base64 = localStorage["file"];
var base64Parts = base64.split(",");
var fileFormat = base64Parts[0].split(";")[1];
var fileContent = base64Parts[1];
var file = new File([fileContent], "file name here", {type: fileFormat});
return file;
}
// Retreived file object
Here is a workaround that I got working with the code below. I'm aware with your edit you talked about localStorage but I wanted to share how I actually implemented that workaround. I like to put the functions on body so that even if the class is added afterwards via AJAX the "change" command will still trigger the event.
See my example here: http://jsfiddle.net/x11joex11/9g8NN/
If you run the JSFiddle example twice you will see it remembers the image.
My approach does use jQuery. This approach also demonstrates the image is actually there to prove it worked.
HTML:
<input class="classhere" type="file" name="logo" id="logo" />
<div class="imagearea"></div>
JS:
$(document).ready(function(){
//You might want to do if check to see if localstorage set for theImage here
var img = new Image();
img.src = localStorage.theImage;
$('.imagearea').html(img);
$("body").on("change",".classhere",function(){
//Equivalent of getElementById
var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.
var reader = new FileReader();
reader.onload = function(e) {
// Create a new image.
var img = new Image();
img.src = reader.result;
localStorage.theImage = reader.result; //stores the image to localStorage
$(".imagearea").html(img);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
});
This approach uses the HTML5 File System API's to read the image and put it into a new javascript img object. The key here is readAsDataURL. If you use chrome inspector you will notice the images are stored in base64 encoding.
The reader is Asynchronous, this is why it uses the callback function onload. So make sure any important code that requires the image is inside the onLoad or else you may get unexpected results.
You could use this lib:
https://github.com/carlo/jquery-base64
then do something similar to this:
//Set file
var baseFile = $.base64.encode(fileObject);
window.localStorage.setItem("file",basefile);
//get file
var outFile = window.localStorage.getItem("file");
an other solution would be using json (I prefer this method)
using: http://code.google.com/p/jquery-json/
//Set file
window.localStorage.setItem("file",$.toJSON(fileobject));
//get file
var outFile = $.evalJSON(window.localStorage.getItem("file"));
I don't think that there is a direct way to Stringify and then deserialize the string object into the object of your interest. But as a work around you can store the image paths in your local storage and load the images by retrieving the URL for the images. Advantages would be, you will never run out of storage space and you can store 1000 times more files there.. Saving an image or any other file as a string in local storage is never a wise decision..
create an object on the global scope
exp: var attmap = new Object();
after you are done with file selection, put your files in attmap variable as below,
attmap[file.name] = attachmentBody;
JSON.stringify(attmap)
Then you can send it to controller via input hidden or etc. and use it after deserializing.
(Map<String, String>)JSON.deserialize(attachments, Map<String,String>.class);
You can create your files with those values in a for loop or etc.
EncodingUtil.base64Decode(CurrentMapValue);
FYI:This solution will also cover multiple file selection
You could do something like this:
// fileObj = new File(); from file input
const buffer = Buffer.from(await new Response(fileObj).arrayBuffer());
const dataUrl = `data:${fileObj.type};base64,${buffer.toString("base64")}`;
localStorage.setItem('dataUrl', dataUrl);
then you can do:
document.getElementById('image').src = localStorage.getItem('dataUrl');