Simple JSZip - Create Zip File From Existing Images - javascript

I'm having a hard time finding easy documentation for JSZip that doesn't involve Base64 or NodeJS. Basically, I have a directory, in which is test.html and a folder called "images". Inside that folder is a bunch of images. I would like to make a zip file out of that folder.
Can anyone help me with some very simple "hello world" type code for this? The documentation on http://stuk.github.io/jszip/ includes things like adding an image from Base64 data or adding a text file that you create in JavaScript. I want to create a .zip file from existing files.
Perhaps the only support for adding images to .zip files with JSZip involves adding them via Base64 data? I don't see that anywhere in the documentation, nor an image-url-to-base64 function, though I did find one elsewhere on StackOverflow.
Any advice?

In a browser you can use an ajax request and use the responseType attribute to get an arraybuffer (if you need IE 9 support, you can use jszip-utils for example) :
var xhr = new XMLHttpRequest();
xhr.open('GET', "images/img1.png", true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var zip = new JSZip();
zip.file("images/img1.png", xhr.response);
}
}
};
xhr.send();
This example is limited because it handles only one file and manually creates the xhr object (I didn't use any library because you didn't mention any) but should show you how to do it.
You can find a more complete example in the JSZip documentation : it uses jQuery promises and jszip-utils to download a list of files and trigger a download after that.
If you use a library to handle the ajax request, be sure to check if you can ask for an arraybuffer. The default is to treat the response as text and that will corrupt your images. jQuery for example should support it soon.

Related

JavaScript Basic Solution for Retrieving Files

I'm very new to JavaScript, so please be patient with me. I've got a CSV file published to the web via Google, which is updated periodically. I have the URL of the file, and I want to write JS code which will retrieve that file when an HTML page is loaded, then convert it into a string so I can manipulate it and scoop out the values I want to place in different elements. The problem is, I have no idea how to request items from different URLs. I'm guessing there's some built-in functionality in JS to do what I want, but I'm completely in the dark on how to find it. Care to help me out?
What you're looking for is the XMLHttpRequest, but I'd recommend using jQuery's $.ajax() function as it decreases the complexity of sending asynchronous requests.
You can use jquery $.ajax or better Fetch API or axios to get the file contents.
Then you need to process it by using something like Papa Parse.
PS. Papa Parse actually supports remote files directly so you can try that.
Sounds like what you're looking for is AJAX.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
doSomethingWith(this.responseText);
}
};
xhttp.open("GET", "http://url/file.csv", true);
xhttp.send();
You could also use jQuery's ajax function :
$.ajax({url: "http://url/file.csv", success: function(result){
doSomethingWith(result);
}});
This way, you get the result as a string which you can then use to retrieve the CSV values - look into the split function for instance.
Be aware that you will not be able to try this locally without a webserver, since your browser will not allow your Javascript to fetch files from your computer. Indeed, your browser implements a mechanism called CORS which restricts HTTP requests heading to a different domain.
Did you publish that .csv to google ? If so , can you program the file to be dumped to your web-content file?
I found I couldn't get files out of google drive with js, a lot of people had problems with this, then I tried to find a solution for it. So instead you can use platforms like github, or host on your server. Then the problem becomes way more straight forward.
I used python to grab the content I wanted , turn into .js file, or json file. Then use javascript to retrieve it.
var data = http://mywebsite.com/my_file.json
or script src = http://my_website/data.js /script
Sorry about the above. Stackoverflow messing with my js. The above is just an example of the script tag 'my_website' needs to be programmes in.
Great place to start with json , and other resource here
https://www.w3schools.com/js/js_json_intro.asp

Read a file in same directory as the JavaScript file

I can load an image file located in the same relative path as the JavaScript file
var imgObj = new Image();
imgObj.src = "images/backdropLevel0.jpg";
But how do I do the same (as simply and with pure JavaScript) for a text file ? (it has some initial data for a webGL game I am working on).
PS. I am not asking about user input from the client's computer using the new File object.
Fetching an image is easy since the browser takes care of all the fetching and rendering. However, loading an arbitrary file into your script requires a couple more lines:
var req = new XMLHttpRequest();
req.onload = function(){
process_webgl_data(this.responseText);
};
req.open('GET', './webgl_init.dat');
req.send();
Where process_webgl_data is whatever you want to do with the text of the file.
EDIT: Two quick things. Remember that request URIs are resolved with respect to the html file rather than the script, and second, here's the documentation for XHR.
You can also archive the same using fetch JavaScript API
Example:
fetch('./webgl_init.dat').then(r=>r.text()).then(process_webgl_data)

How to download images on mobile to upload to my server?

I'm writing an application in phonegap/cordova. In the application, users have a profile and they can select facebook images to include with their profile.
When they select the images for their profile, I want to upload those specific images to my own server.
I did some research and was able to write some code that download the images but I didn't test it on mobile until after I wrote the code.
I used an XML HTTP Request to download the image as a blob. However, upon testing in mobile, I got errors that the blob.size parameter was not set.
I checked in the browser and indeed the blob.size parameter exists. In mobile, the blob.size parameter is undefined. This led me to believe that the webkit that is on my phone does not support blobs and therefore cannot download the images as blobs.
I have 2 questions really:
1) Is my assessment correct that the blob is not being downloaded because the webkit does not support blob?
2) If 1 is true what is the proper way to download an image in cordova and then upload it to my own server? Alternatively, is there any way I can just tweak my code so that it works on mobile? Also I should note that since the files are already downloaded to my phone, is there a way to simply access them in the local storage instead of downloading them again and then upload that file to my server?
My current code to download as a blob is below:
function xhrPromise(url){
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var myBlob = this.response;
return myBlob;
}
};
xhr.send();
}
Based on further research I'm wondering if the solution is to use the cordova file-transfer plugin?
Any suggestions would be greatly appreciated.
1) Webkit supports blob through HTML File API. Read: Exploring the FileSystem APIs
2) I will try to point you into the right direction. What I would do, if I wanted to download an image then re-upload it to another server.
Use Cordova's FileTransfer Plugin to download the picture and write it to a temp location in the SD Card (Android) or the App's Document folder (iOS).
If the image is under 2MB, use a simple HTML tag to link to the downloaded picture, using CDVFILE protocol, <img src="cdvfile://localhost/persistent/temp/image.jpg" /> (for Android) then use AJAX to post it to your server, by encoding the image into base64. Read: How to convert image into base64 string using javascript.
If the image is over 2MB, use Cordova's FileTransfer Plugin to upload.
When using Cordova's FileTransfer Plugin, you will come across HTML File API, I strongly suggest you keep this link as a reference. Read: Exploring the FileSystem APIs
The reason why I would prefer using base64 encoding is because 1) I don't like to rely on Cordova plugins, they used to be super buggy. 2) You can save base64 strings into MySQL (but anything over 2MB will impact your server and the device encoding it).

Downloading and then uploading files with JavaScript

Now first of all, I'm making a UserScript, meaning that I don't own the servers from which I download files or the servers to which I upload files.
So I need to download a file from a server (needs to be any type, not just text files), and then somehow submit that file to a file upload form on another website. Is that possible? At first I was wondering if I'd be able to submit the file directly from one server to the other, but I don't think that's possible.
So is there any way I can do this? I can use jQuery as well.
As long as you won't be blocked by XSS prevention, load the data using an XMLHttpRequest then post it to the other site.
Here is a very basic functional example:
var xhr = new XMLHttpRequest();
xhr.open("get", "http://www.example.com/file", true);
xhr.onload = function () {
xhr.close();
var xhr2 = new XMLHttpRequest();
xhr2.open("post", "http://www.example2.com/form", true);
xhr2.send(xhr.response);
}
xhr.send();
I would advise that you add some code to catch errors
For more details on XMLHttpRequests, the documentation can be found on MDN here, with instructions on how to use it on MDN here

Fetching zipped text file and unzipping in client browsers, feasible in Javascript?

I am developing a web page containing Javascript. This js uses static string data (about 1-2 MB) which is stored in a flat file. I could compress it with gzip or any other algorithm to reduce the transfer load.
Would it be possible to fetch this binary file with Ajax and decompress it into a string (which I could split later) in the client browser. If yes, how can I achieve this? Does anyone have a code example?
And another library or site is this one, although it has few examples it has some thorough test cases that can be seen.
https://github.com/imaya/zlib.js
Here are some of the complex test cases
https://github.com/imaya/zlib.js/blob/master/test/browser-test.js
https://github.com/imaya/zlib.js/blob/master/test/browser-plain-test.js
The code example seems very compact. Just these two lines of code...
// compressed = Array.<number> or Uint8Array
var gunzip = new Zlib.Gunzip(compressed);
var plain = gunzip.decompress();
If you look here https://github.com/imaya/zlib.js/blob/master/bin/gunzip.min.js you see they have the packed js file you will need to include. You might need to include one or two of the others in https://github.com/imaya/zlib.js/blob/master/bin.
In any event get those files into your page and then feed the GUnzip objects your pre-gzipped data from the server and then it will be as expected.
You will need to download the data and get it into an array yourself using other functions. I do not think they include that support.
So try these examples of download from https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data
function load_binary_resource(url) {
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
return req.responseText;
}
// Each byte is now encoded in a 2 byte string character. Just AND it with 0xFF to get the actual byte and then feed that to GUnzip...
var filestream = load_binary_resource(url);
var abyte = filestream.charCodeAt(x) & 0xff; // throw away high-order byte (f7)
=====================================
Also there is Node.js
Question is similar to
Simplest way to download and unzip files in Node.js cross-platform?
There is this example code at nodejs documentation. I do not know how much more specific it gets than that...
http://nodejs.org/api/zlib.html
Just enable the Gzip compression on your Apache and everything will be automatically done.
Probably you will have to store the string in a .js file as a json and enable gzip for js mime type.
I remember that I used js-deflate for off-linne JS app with large databases (needed due to limitations of local storage) and worked perfectly. It depends on js-base64.

Categories

Resources