I want zip a pdf or some other format like excel, ppt etc using jszip.
How to zip this format in jszip?
My code is as below
<BODY>
<a id ='file' href="data/some.pdf" type="application/pdf; length=432628">Some.pdf</a>
<input id="button" type="button" onclick="create_zip()" value="Create Zip"></input>
</BODY>
<SCRIPT>
function create_zip() {
var data = document.getElementById('file');
var zip = new JSZip();
zip.add(data, {base64: true});
content = zip.generate();
location.href = "data:application/zip;base64," + content;
}
</SCRIPT>
What I want is that I will get the path of the file from the a element in the html. I want to zip the pdf using jszip
jsfiddle
JSZipUtils may be useful for you. This is the example for the documentation:
JSZipUtils.getBinaryContent("path/to/picture.png", function (err, data) {
if(err) {
throw err; // or handle the error
}
var zip = new JSZip();
zip.file("picture.png", data, {binary:true});
}
Which can be easily adapted to your case:
function create_zip() {
var url = document.getElementById('file').href;
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
throw err; // or handle the error
}
var zip = new JSZip();
zip.file("Some.pdf", data, {binary:true});
content = zip.generate();
}
}
Related
What I am trying to do : I have a cloud page where the user can upload CSV file. When user clicks on the “upload” button the a function called getBase64() is called (please refer the below code). The getBase64() function will encode the uploaded file and post it to a second cloud page.The second cloud page then takes the posted data.
Note: I am trying to adapt this solution to my need (csv file) by referring to this article partially https://sfmarketing.cloud/2020/02/29/create-a-cloudpages-form-with-an-image-file-upload-option/
What’s the problem : When I try to click the the “upload” button the page is not taking me to the second CloudPage. Please could anyone let me know what I am doing wrong here ?
Here is the code:
CloudPage 1
<input id="file" type="file" accept=".csv">
<br>
<button id="button">Upload</button>
<script runat="client">
document.getElementById("button")
.addEventListener("click", function() {
var files = document.getElementById("file").files;
if (files.length > 0) {
getBase64(files[0]);
}
});
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
//prepare data to pass to processing page
var fileEncoded = reader.result;
var base64enc = fileEncoded.split(";base64,")[1];
var fullFileName = document.getElementById("file").files[0].name;
var fileName = fullFileName.split(".")[0];
var assetName = fullFileName.split(".")[1];
fetch("https://cloud.link.example.com/PAGE2", { //provide URL of the processing page
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
base64enc: base64enc,
fileName: fileName,
assetName: assetName
})
})
.then(function(res) {
window.alert("Success!");
})
.catch(function(err) {
window.alert("Error!");
});
};
reader.onerror = function(error) {
console.log('Error: ', error);
};
}
</script>
CloudPage 2
<script runat="server">
var jsonData = Platform.Request.GetPostData();
var obj = Platform.Function.ParseJSON(jsonData);
</script>
I do not see any errors in the code and when I click on the upload button I get a success message but it does not take me to the second page. Please can anyone guide me how to retrieve this posted data in second page as I am not able to get the encoded data in page 2?
The web page is made, it is assembled modularly. I use node js, the node-static server.
I need to implement downloading a file, that is, from a computer and then to the device so that the file is downloaded by the button.
While I’m trying from the computer to my own computer, on the path I need, but it doesn’t work out in any way. Already tried all sorts of npm modules.
Here is the html code and the client file where the sending occurs:
<form name="upload" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="submit" name="submit" value="Обновить">
</form>
fileId = file.name;
var formData = new FormData();
formData.append("file", document.querySelector('input').files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "savesettings", true);
xhr.setRequestHeader('X-File-Id', fileId);
xhr.addEventListener("load", function() {
console.log("Done:", xhr.status);
});
xhr.send(formData);
Here is the script that was supposed to accept the request and save the file to the desired directory, here it seems to me the main problems:
if (req.url == '/savesettings' && req.method == 'POST') {
let fileId = req.headers['x-file-id'];
let filePath = path.join('/home/alexandr/alexandr/web-cfg/uploads', fileId);
if (!uploads[fileId]) uploads[fileId] = {};
let upload = uploads[fileId];
let fileStream;
upload.bytesReceived = 0;
fileStream = fs.createWriteStream(filePath, {
flags: 'w'
});
console.log("fileStream1:", fileStream);
req.on('data', function(data) {
console.log("data:", data.length);
upload.bytesReceived += data.length;
console.log("bytes received", upload.bytesReceived);
});
req.pipe(fileStream);
console.log("req.pipe:", req.pipe(fileStream));
console.log("123", req.data);
fileStream.on('close', function() {
if (upload.bytesReceived <= 50000) {
debug("Upload finished");
delete uploads[fileId];
res.end("Success " + upload.bytesReceived);
} else {
debug("File unfinished, stopped at " + upload.bytesReceived);
res.end();
}
});
fileStream.on('error', function(err) {
debug("fileStream error");
res.writeHead(500, "File error");
res.end();
});
}
From what I know about HTML, I would say that it would be mostly in your HTML rather than your server. If you can access the file by typing in the path to the file after the domain in the URL, then you should be able to access it via the website.
A simple HTML example of this would look like this:
<a href="path/to/file.js" download>
You could then style the link with CSS to look however you want it to.
i am trying to convert the content of an editable div to a text file and store it in azure. It's actually a css file (format) but i guess that text will have the same output. This is what i got so far:\
var sasKey = "xxxxxxxxxxxxxxx";
var blobUri = xxxxx.blob.core.windows.net";
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sasKey);
function Save() {
var blobData = document.getElementById("CONTENT").innerText;
var myBlob = new Blob(blobData, "plain/text");
blobService.createBlockBlobFromBrowserFile('style',
"test.txt",
myBlob,
(error, result) => {
if (error) {
// Handle blob error
} else {
console.log('Upload is successful');
}
});
}
HTML:
<div id="CONTENT" contenteditable="true" spellcheck="false">so here we have text</div>
<input type="button" value="save" onclick="Save()"/>
i get the following error:
Uncaught TypeError: Failed to construct 'Blob': The provided value cannot be converted to a sequence.
The Blobobject takes a list as its first parameter.
Try this instead:
var myBlob = new Blob([blobData], { type: "plain/text" });
https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob
to be complete this is what i used to upload a text (txt) file
<script>azure-storage.blob.min.js</script>
JS
var sasKey = "xxxxxxxxxxxxxxx";
var blobUri = xxxxx.blob.core.windows.net";
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sasKey);
function Save() {
var blobData = document.getElementById("CONTENT").innerText;
blobService.createContainerIfNotExists('container', (error, container) => {
if (error) {
// Handle create container error
} else {
console.log(container.name);
}
});
blobService.createBlockBlobFromText('container', "test.txt", blobData,
(error, result) => {
if (error) {
// Handle blob error
} else {
console.log('Upload is successful');
}
});
}
HTML
<div id="CONTENT" contenteditable="true" spellcheck="false">so here we have text</div>
<input type="button" value="save" onclick="Save()"/>
I am programming an app with elecrtonjs and got stuck.
So on my page there is this HTML:
<a href="./step1.html" id="next"><span onclick="writeToFile();return false">Next ></span></a`>
And in the javasriptfile I am saving stuff to a file in the directory:
var fs = require('fs');
function writeToFile() {
//alert(document.getElementsByTagName("input").length);
var text = "";
// Change the content of the file as you want
// or either set fileContent to null to create an empty file
for (var i = document.getElementsByTagName("input").length - 1; i >= 0; i--) {
text += document.getElementsByTagName("input")[i].getAttribute("name")+":\n";
text += document.getElementsByTagName("input")[i].value+"\n";
}
// The absolute path of the new file with its name
var filepath = "mynewfile.txt";
fs.appendFile(filepath, text, (err) => {
if (err) throw err;
console.log("The file was succesfully saved!");
});
}
The code redirects properly but does not append the user-input in to the specified file.
Am I timing the stuff wrong? I tried
onbeforeunload
Thanks for the help.
As Chris Li already stated, you should use
window.location.href = "./step1.html"
and remove the href field of your link.
I have a zip file which is a Visual Basic project. What I'm trying to see is if I can add my web app as a directory inside this zip archive so I can easily export my web apps as native windows apps
I tried the Ajax method from the documentation and it worked fine on my hard drive when loaded in Firefox, but it's not calling when from my website!
$(document).ready(function() {
$(".download").on("click", function() {
JSZipUtils.getBinaryContent('YourWinApp.zip', function(err, data) {
if(err) {
throw err; // or handle err
}
var zip = new JSZip(data);
zip.file("Hello.txt", "Hello World\n");
var folder = zip.folder("images");
folder.file("folder.txt", "I'm a file in a new folder");
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "example.zip");
});
});
});
I tried the Ajax method from the documentation and it worked perfectly! (I didn't link to the right file lol)
$(document).ready(function() {
$(".download").on("click", function() {
JSZipUtils.getBinaryContent('YourWindowsApp.zip', function(err, data) {
if(err) {
throw err; // or handle err
}
var zip = new JSZip(data);
zip.file("Hello.txt", "Hello World\n");
var folder = zip.folder("images");
folder.file("folder.txt", "I'm a file in a new folder");
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "example.zip");
});
});
});