jszip creating empty txt files of images and zip them - javascript

I am using this code to download these Images but This programming making a txt files with these names and with type jpeg . why this is happening ? this programm is not working on chrome due to cross site but on firefox in zip file empty txt files are.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script type="text/javascript" src="https://fastcdn.org/FileSaver.js/1.1.20151003/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js" type="text/javascript">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip-utils/0.0.2/jszip-utils.min.js" type="text/javascript">
</script>
<script>
var urls = [
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0397.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0398.jpg",
"https://s3.amazonaws.com/ais-django/Events/Test1/DSC_0488.jpg"
];
var nombre = "Zip_img";
//The function is called
compressed_img(urls, nombre);
function compressed_img(urls, nombre) {
var zip = new JSZip();
var count = 0;
var name = nombre + ".zip";
urls.forEach(function(url) {
JSZipUtils.getBinaryContent(url, function(err, data) {
if (err) {
throw err;
}
zip.file(url, data, {
binary: true
});
count++;
if (count == urls.length) {
zip.generateAsync({
type: 'blob'
}).then(function(content) {
saveAs(content, name);
});
}
});
});
}
</script>
</body>
</html>

Related

single and multiple file upload

I'm facing issue. single and multiple file uploaded file. Then multiple file upload successfully but when single file one by one upload then last one upload other are override by last one. Please help me to find out this problem solution. As you can see below code it's work properly for multiple upload file and send data by ajax then get array value all images but when upload single upload one by one then last one image data get only in ajax data in. please help me to provide me solution.
index.php
`
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
</style>
<body>
<form id="myForm" method="post">
<input type="file" id="files" class="file_uploader_file" name="files[]" multiple="true" accept="image/*" />
<p class="validateError" id="imgerror" style="color:red;display:none;">Please select your design.</p>
<input type="button" id="fees_stream_submit1" name="submit">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
(function () {
$(document).on('click', '#fees_stream_submit1', function (e) {
var myfiles = document.getElementById("files");
// var myfiles = $('#files').val();
var files = myfiles.files;
var form = new FormData();
alert(files.length);
for (i = 0; i < files.length; i++) {
form.append('file' + i, files[i]);
}
$.ajax({
url: "fileuploadmultidata.php",
type: "POST",
data: form,
contentType: false,
processData: false,
success: function (result) {
// alert(result);
}
});
});
})();
$(document).ready(function () {
var imgCnt = 0;
var onebyoneImg = [];
var countImg = 1;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
// var f = new File([""], files[i]);
var fileReader = new FileReader();
fileReader.onload = (function (e) {
imgCnt++;
alert(imgCnt);
var file = e.target;
$("<span class='pip'><div class=\"file_uploaded_view img-thumb-wrapper image-preview-height\">" +
"<img class=\"img-thumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\" style='heigh:100px;width:100px'/>" +
"<br/><span class='remove'><i class='fa fa-trash'></i></span></span>" +
"</div>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".img-thumb-wrapper").remove();
imgCnt--;
});
});
fileReader.readAsDataURL(f);
}
console.log(f);
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
</body>
</html>
`
**fileuploadmultidata.php**
`<?php
echo "<pre>";
print_r($_FILES);die();
?>`
The behaviors of file uploading will be like that only see https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_files
To achieve your requirement you need to store file values in variable and use.
var storeMultiFiles = [];
var file = $(file_id)[0].files;
for(var l=0; l<file.length; l++){
var fileData = file[l];
(function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(oFREvent){
storeMultiFiles.push(oFREvent.target.result)
};
})(fileData);
}
Use files details using "storeMultiFiles" for show, save, update and delete for selected.

How do i check my file (file is : a text file that am storing all the configuration)is empty or not in JavaScript

I am trying following function to check file data exist or not if not exist it will display validation message on console.
$("#eventDelete").click(function() {
const fs = require('fs')
fs.readFile('safeList.txt', (err, data) => {
if (err) throw err;
alert(data);
if (data == null) {
$('#event_responseErr').html("no records to delete.");
return false;
}
}
});
You can use something like this or see this : https://www.codegrepper.com/code-examples/javascript/filereader+javascript+example
<html>
<head>
<title>Read Text File</title>
</head>
<body>
<input type="file" name="inputfile"
id="inputfile">
<br>
<pre id="output"></pre>
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
if(fr.result){
alert('Data Found');
}else{
alert('No Data Found');
}
// document.getElementById('output')
// .textContent=fr.result;
}
fr.readAsText(this.files[0]);
})
</script>
</body>
</html>

How to take the console output of html file into phantomjs

I am running qunit Test using html file in one file and that html file i am running from phantom js.
When I am running html file through browser i am getting output in console but when i am trying to run using phantom js i am not getting the console output in another js file from where i am calling html file.
I am providing both Files:
HTML File :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JUnit reporter for QUnit</title>
<link rel="stylesheet" href="qunit.css">
<script src="qunit.js"></script>
<script>
QUnit.config.reorder = false;
</script>
<script src="qunit-reporter-junit.js"></script>
<script src=" http://requirejs.org/docs/release/2.2.0/minified/require.js"></script>
<script>
QUnit.jUnitDone(function(data) {
var console = window.console;
if (console) {
console.log(data.xml);
}
});
</script>
<script src="qunit-reporter-junit.test.js"></script>
</head>
<body>
<div id="qunit"></div>
</body>
</html>
Js file :
var system = require('system');
var fs = require('fs');
var page = require('webpage').create();
if (system.args.length === 1) {
console.log('Pass the path/to/testfile.js as argument to run the test.');
phantom.exit();
} else {
var url = "file:///C:/Users/Admin/Desktop/js/index.html"; // e.g. 'test/unit/tests.html'
console.log("Opening " + url);
}
page.open(url, function (status) {
console.log("Status: " + status);
if (status === "success") {
setTimeout(function () {
var path = 'results.xml';
var output = page.evaluate(function () {
// wants to take console output from html page
.....................................?
});
fs.write(path, output, 'w');
console.log("Wrote JUnit style output of QUnit tests into " + path);
console.log("Tests finished. Exiting.");
phantom.exit();
}, 3000);
} else {
console.log("Failure opening" + url + ". Exiting.");
phantom.exit();
}
});
can anyone suggest me how to take the console output from html file ?
Thanks In Advance.
If your test is similar to this example then to get test results you should request the contents of #qunit-testresult element.
var output = page.evaluate(function(){
return document.getElementById("qunit-testresult").innerText
});

SheetJS read excel file, my file is not read

So I am trying to use the SheetJS javascript to read in some excel files. I download the SheetJS and I have copied the xlsx.full.min.js in same directory as my html file. However, I do not get it to work. So I tried the code below. The problem is that it does not reach the alert('finished reading'); line. So I do not know if there was a problem reading the source file or what the problem exactly is. I hope somebody can help me with this! Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
</style>
</head>
<body>
<p><input type="file" name="xlfile" id="xlf" /> ... or click here to select a file</p>
<script src="xlsx.full.min.js"></script>
<script>
function handleFile(e) {
//Get the files from Upload control
var files = e.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (e) {
var data = e.target.result;
alert(data);
var result;
alert('reading now');
var workbook = XLSX.read(data, { type: 'binary' });
alert('finished reading');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) { /* iterate through sheets */
//Convert the cell value to Json
var roa = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
if (roa.length > 0) {
result = roa;
}
});
//Get the first column first cell value
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}
var xlf = document.getElementById('xlf');
if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>

My node.js server script is serving the index.html fine, but not the CSS or other static files

I am trying to write a Node.js project from a tutorial, but the server.js file does not seem to be working properly:
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var cache = {};
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: not found');
response.end();
}
function sendFile(response, filePath, fileContents) {
response.writeHead(
200,
{"content-type": mime.lookup(path.basename(filePath))}
);
response.end(fileContents);
}
function serveStatic(response, cache, absPath) {
if (cache[absPath]) {
sendFile(response, absPath, cache[absPath]);
} else {
fs.exists(absPath, function(exists) {
if (exists) {
fs.readFile(absPath, function(err, data) {
if (err) {
send404(response);
} else {
cache[absPath] = data;
sendFile(response, absPath, data);
}
});
} else {
send404(response);
}
});
}
}
var server = http.createServer(function(request, response) {
var filePath = false;
if(request.url == '/') {
filePath = 'public/index.html';
} else {
filePath = '/public/' + request.url;
}
var absPath = './' + filePath;
serveStatic(response, cache, absPath);
});
server.listen(26353, function() {
console.log("Listening...");
});
When I go to my URL the index.html content is displayed, but none of the stylesheets or attached files from the index.html are displayed, I get:
GET http://myURL.com/stylesheet/style.css 404 (NOT FOUND)
Here is my index.html:
<html>
<head>
<title>Chat</title>
<link rel='stylesheet' href='/stylesheet/style.css'></link>
</head>
<body>
<div id='content'>
<div id='room'></div>
<div id='room-list'></div>
<div id='messages'></div>
<form id='send-form'>
<input id='send-message' />
<input id='send-button' type='submit' value='Send' />
<div id='help'>
Chat commands:
<ul>
<li>.....</li>
</ul>
</div>
</form>
</div>
<script src='/socket.io/socket.io.js' type='text/javascript'></script>
<script src='http://code.jquery.com/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='/javascript/chat.js' type='text/javascript'></script>
<script src='/javascript/chat_ui.js' type='text/javascript'></script>
</body>
</html>
I'm not sure what is wrong.
My project directory has the server.js, the node-modules and the public folder, the public folder has a stylesheet directory and javascript folder where the files are.
My web host has is set up so that http://myURL.com/node/ is where port 26353 is bound to (don't know if that's the right word). So if I go to http://myURL.com/node I see the index.html file but none of the stylesheets or javascript works.
Sending file is not so trivial in node.js. There is a code from my framework
core.sendFile = function(filename, context)
{
if (fs.exists(filename, function (exists)
{
if (exists) fs.stat(filename, function (err, stats)
{
if (err) core.catch_err(err);
else if (stats && !stats.isDirectory())
{
var filestream = new fs.ReadStream(filename);
var mimme = mime.lookup(filename);
context.response.writeHead(200, {'Content-Type': mimme });
filestream.pipe(context.response);
filestream.on("error", function (err) { context.response.statusCode = "500"; context.response.end("Server error"); core.log("Server error while sending " + filename, "err"); });
context.response.on("close", function () { filestream.destroy(); });
core.logger.log("Sending file " + filename);
}
});
else core.not_found(context);
}));
}
The idea is to read and write file as a stream, and to process some errors and closing of streams. "Core" is just a library object.
remove the first / from your url, so it should be stylesheet/style.css instead of /stylesheet/style.css

Categories