How do i get images file name from a given folder [duplicate] - javascript

This question already has answers here:
How to load all the images from one of my folder into my web page, using Jquery/Javascript
(14 answers)
jQuery pull images from directory
(4 answers)
Closed 8 years ago.
I have got a task to display all images inside a folder using jquery.
For that i used the code
var imageFolder = '../../Images/Avatar/';
var imgsrc = imageFolder +'';
I need to get the images file name inside that folder avatar. How can I get the file name. There are lot of image files in that avatar folder also has some txt files.I only need jpg,png,gif images only.

try this way
HTML CODE:
<div id='fileNames'> </div>
JQUERY CODE:
var fileExt = {},
fileExt[0]=".png",
fileExt[1]=".jpg",
fileExt[2]=".gif";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: '../../Images/Avatar/',
success: function (data) {
$("#fileNames").html('<ul>');
//List all png or jpg or gif file names in the page
$(data).find("a:contains(" + fileExt[0] + "),a:contains(" + fileExt[1] + "),a:contains(" + fileExt[2] + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
$("#fileNames").append( "<li>" + filename + "</li>");
});
$("#fileNames").append('</ul>');
}
});
Basic logic referred from this SO question Here
Happy Coding :)

I don't know that it will work or not but you can try this
Give the name of image 1,2,3,4.....
and than show image using for loop like.
var imageFolder = '../../Images/Avatar/';
var imgsrc="";
for(var i=1; i <= totalImage; i++){
imgsrc= imageFolder +i;
}

Related

How to save the file by giving the file name from grid row containing columns,name,date,device

I have a Grid view With Name time , device , Upload control columns , When i click upload in Grid view , files will be uploaded and saved in a folder, but i need to save the file with name_time_device..
How to do it any help??
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
//FileUploadData.tName = Request.QueryString["name"];
//string fname = context.Server.MapPath("~/FileUploads/") + FileUploadData.Name + "_" + FileUploadData.Id + "/" + DateTime.Now.ToString("ddMMyyyy") + "/" + FileUploadData.deviceID + "_" +
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "application/x-zip-compressed";
context.Response.Write("File Uploaded Successfully!");
}
File uploading and saving i am doing in javascript. the file is zipped..and saving it in uploads folder, but it need to be saved with name_id_date_device.zip..
I am using a function In that function i am using ajax call , above code is my generic handler to save the files..
file saving is from function, here while saving only i need to pass id_name_device so which ever user clicks upload and upload files his file will be saved by his id_name_device.zip..
Help??
Can you please speicify you are having problem in getting name, time, device from gridview or you have issue with file saving with name "name_id_date_device.zip"?
if you problem is saving file with a specific name and you are ok to get name, time or device from gridview then you should change this:
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
TO
string fname = context.Server.MapPath("~/uploads/" + "name_id_date_device.zip");
in this way your file will be saved with this given name.
if you want to add your flag with file name just concat it with your filename when you are saving.
string fname = context.Server.MapPath("~/uploads/" + "what_flag_name_time" + file.FileName);
.and if you have anyother problem please be more specific. Thanks

upload file to google drive folder instead of user browser javascript/jsquery

My current script uses the code below to download a CSV file to local drive,
function table2CSV() {
var dataURL = '',
fieldSeparator = ',',
textField = '"',
lineSeparator = '\n',
regExpTesto = /(")/g,
regExp = /[";]/;
$('table tr').each(function() {
var dataRow = '';
if ($('input:checkbox', this).is(':checked') || $(this).is(':first- child'))
{
$('td', this).not(':last').each(function() {
var value = $(this).text();
if (dataRow !== '') dataRow += fieldSeparator;
if (regExp.test(value)) {
value = textField + value.replace(regExpTesto, '$1$1') + textField;
}
dataRow += value;
});
if (dataURL !== '') dataURL += lineSeparator;
dataURL += dataRow;
}
});
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
}
The download is done bye this line as far as I can tell :
window.location.href = 'data:text/csv;charset=utf-8;base64,' + btoa(dataURL);
I would like to be able to have it download(upload/saved) to a shared google drive folder instead.
I have seen similar questions on the forum but can't seem to see how to point the download to a shared google-drive folder.
What must code must be added/changed in order to achieve this ?
Thank you
EDIT: Nevermind, just realised they say it does not support data URIs:
Data URIs and file:// URLs are not supported
I will keep this answer in case anyone else searches for non-data URI uploading
Having a quick look, I came upon Save to Drive
While this might not be exactly what you want, it looks like an easy way to add the ability to save the contents of any URI (hopefully a data URI too) to Google Drive, like so:
<script src="https://apis.google.com/js/platform.js" async defer></script>
<div class="g-savetodrive"
data-src="//example.com/path/to/myfile.pdf"
data-filename="My Statement.pdf"
data-sitename="My Company Name">
</div>

how do I remove an item that is set to upload?

I have created an uploader using javascript and php. The problem is that I only want to allow specific file types. I have it letting the user know the file is not valid but I am not sure how to remove the file from being uploaded. Can anyone tell me how to remove the upload?
multiUploader.prototype._preview = function(data) {
this.items = data;
if (this.items.length > 0) {
var html = "";
var uId = "";
for (var i = 0; i < this.items.length; i++) {
uId = this.items[i].name._unique();
if (typeof this.items[i] != undefined) {
if (self._validate(this.items[i].type) <= 0) {
var errorClass = '<h3 class="text-danger">Invalid file format' + this.items[i].name + '</h3>'
jQuery(".errorContent").append(errorClass);
jQuery.remove(this.items[i]);
}
html += '<div class="dfiles" rel="' + uId + '"><h5>' + this.items[i].name + '</h5><div id="' + uId + '" class="progress" style="display:none;"></div></div>';
}
}
jQuery("#dragAndDropFiles").append(html);
}
}
This is not all of the code, just the function that displays my error message and also shows the uploaded file on the page. I tried it with jQuery.remove but it does not work. Any ideas are appreciated
what is a "file type"? I could send you a .php file that ends in .jpg, would you accept that? (I hope not!). Let the user upload the files with a warning that files X, Y, Z are not going to be accepted based on extension mismatch. Then actually test their content to see if the files are truly what their extension claims, because -and this part is important- your javascript in no way guarantees that what you're going to get is what you wrote your scripts to allow. Changing your script in my browser is a matter of opening my devtools and rewriting your script, then hitting ctrl-s. Now my browser will be running my code, not your code, and happily upload my files anyway.
Always, always, server-verify the user data.

How to save the current webpage with casperjs/phantomjs?

Is there a way to save the current webpage by using casperjs or phantomjs?
I tried to get the html and save it into a file. But the resulting file was a lot different from the screenshot of that time (with casper.capture). Is there a way to save the current webpage?
Andrey Borisko suggested to use the disk cache to retrieve the resources. My solution is not that efficient, but you don't need to decompress text files.
I use XMLHttpRequest to retrieve all resources after I registered them with the resource.received event handler. I then filter the resources into images, css and fonts. The current limitation is that remote resource paths that contain something like ../ or ./ are not handled correctly.
I retrieve the current page content with getHTML and iterate over all captured resources to replace the path used in the markup, that is identified by a portion of the complete resource URL, with a randomly generated file name. The file extension is created from the content type of the resource. It is converted using mimeType from this gist.
Since CSS files may contain background images or fonts, they have to be processed before saving to disk. The provided loadResource function loads the resource, but does not save it.
Since XMLHttpRequest to download the resources the script has to be invoked with the --web-security=false flag:
casperjs script.js --web-security=false
script.js
var casper = require("casper").create();
var utils = require('utils');
var fs = require('fs');
var mimetype = require('./mimetype'); // URL provided below
var cssResources = [];
var imgResources = [];
var fontResources = [];
var resourceDirectory = "resources";
var debug = false;
fs.removeTree(resourceDirectory);
casper.on("remote.message", function(msg){
this.echo("remote.msg: " + msg);
});
casper.on("resource.error", function(resourceError){
this.echo("res.err: " + JSON.stringify(resourceError));
});
casper.on("page.error", function(pageError){
this.echo("page.err: " + JSON.stringify(pageError));
});
casper.on("downloaded.file", function(targetPath){
if (debug) this.echo("dl.file: " + targetPath);
});
casper.on("resource.received", function(resource){
// don't try to download data:* URI and only use stage == "end"
if (resource.url.indexOf("data:") != 0 && resource.stage == "end") {
if (resource.contentType == "text/css") {
cssResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("image/") == 0) {
imgResources.push({obj: resource, file: false});
}
if (resource.contentType.indexOf("application/x-font-") == 0) {
fontResources.push({obj: resource, file: false});
}
}
});
// based on http://docs.casperjs.org/en/latest/modules/casper.html#download
casper.loadResource = function loadResource(url, method, data) {
"use strict";
this.checkStarted();
var cu = require('clientutils').create(utils.mergeObjects({}, this.options));
return cu.decode(this.base64encode(url, method, data));
};
function escapeRegExp(string) {
// from https://stackoverflow.com/a/1144788/1816580
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(find, replace, str) {
// from https://stackoverflow.com/a/1144788/1816580
return str.replace(find, replace);
}
var wrapFunctions = [
function wrapQuot1(s){
return '"' + s + '"';
},
function wrapQuot2(s){
return "'" + s + "'";
},
function csswrap(s){
return '(' + s + ')';
}
];
function findAndReplace(doc, resources, resourcesReplacer) {
// change page on the fly
resources.forEach(function(resource){
var url = resource.obj.url;
// don't download again
if (!resource.file) {
// set random filename and download it **or** call further processing which in turn will load ans write to disk
resource.file = resourceDirectory+"/"+Math.random().toString(36).slice(2)+"."+mimetype.ext[resource.obj.contentType];
if (typeof resourcesReplacer != "function") {
if (debug) casper.echo("download resource (" + resource.obj.contentType + "): " + url + " to " + resource.file);
casper.download(url, resource.file, "GET");
} else {
resourcesReplacer(resource);
}
}
wrapFunctions.forEach(function(wrap){
// test the resource url (growing from the back) with a string in the document
var lastURL;
var lastRegExp;
var subURL;
// min length is 4 characters
for(var i = 0; i < url.length-5; i++) {
subURL = url.substring(i);
lastRegExp = new RegExp(escapeRegExp(wrap(subURL)), "g");
if (doc.match(lastRegExp)) {
lastURL = subURL;
break;
}
}
if (lastURL) {
if (debug) casper.echo("replace " + lastURL + " with " + resource.file);
doc = replaceAll(lastRegExp, wrap(resource.file), doc);
}
});
});
return doc;
}
function capturePage(){
// remove all <script> and <base> tags
this.evaluate(function(){
Array.prototype.forEach.call(document.querySelectorAll("script"), function(scr){
scr.parentNode.removeChild(scr);
});
Array.prototype.forEach.call(document.querySelectorAll("base"), function(scr){
scr.parentNode.removeChild(scr);
});
});
// TODO: remove all event handlers in html
var page = this.getHTML();
page = findAndReplace(page, imgResources);
page = findAndReplace(page, cssResources, function(cssResource){
var css = casper.loadResource(cssResource.obj.url, "GET");
css = findAndReplace(css, imgResources);
css = findAndReplace(css, fontResources);
fs.write(cssResource.file, css, "wb");
});
fs.write("page.html", page, "wb");
}
casper.start("http://www.themarysue.com/").wait(3000).then(capturePage).run(function(){
this.echo("DONE");
this.exit();
});
The magic happens in findAndReplace. capturePage is completely synchronous so it can be dropped anywhere without much head ache.
URL for mimetype.js
No, I don't think there is an easy way to do this as phantomjs doesn't support rendering pages in mht format (Render as a .mht file #10117). I believe that's what you wanted.
So, it needs some work to accomplish this. I did something similar, but i was doing it the other way around I had a rendered html code that I was rendering into image/pdf through phantomjs. I had to clean the file first and it worked fine for me.
So, what I think you need to do is:
strip all js calls, like script tags or onload attributes, etc..
if you have access from local to the resources like css, images and so on (and you don't need authentication to that domain where you grab the page) than you need to change relative paths of src attributes to absolute to load images/etc.
if you don't have access to the resources when you open the page then I think you need to implement similar script to download those resources at the time phantomjs loads the page and then redirect src attributes to that folder or maybe use data uri.
You might need to change links in css files as well.
This will bring up the images\fonts and styling you are missing currently.
I'm sure there are more points. I'll update the answer if you need more info, once I see my code.

Use Javascript to scan a local directory and then update an Anchor tag with the "latest" file

I'm trying to create a simple HTML page that will basically, load up some javascript, and check my direction (../Files)
the Files folder contains
file_001.txt
file_002.txt
file_003.txt
I then want javascript to use the latest one (file_003.txt), and update a anchor tag with the id of "file_download".
Would anyone by any chance have an idea how to do this?
The reason is, lets say I have a terms and conditions PDF file that is T&C_001.pdf and download the line a new terms and conditions is released. so we keep the T&C_001.pdf for any old records and we upload T&C_002.pdf. Now this will not need any HTML knowledge or even Javascript. The owner of the site would just need to add a new file with 002 on the end.
though, not fully accurate, you could try
<script type="text/javascript">
function getLatest(location, filename, ext, readyCallback, index) {
var tgIndex = typeof index === 'undefined' ? 1 : index;
$.ajax({
type: 'HEAD',
url: location + '/' + filename + '-' + index + '.' + ext,
success: function() {
getLatest(location, filename, ext, readyCallback, tgIndex + 1);
},
error: function() {
if (tgIndex > 1) {
readyCallback(location + '/' + filename + '-' + (tgIndex-1) + '.txt');
return;
}
readyCallback();
}
});
}
getLatest('linkToSite', 'file', 'txt', function(filename) {
if (typeof filename === 'undefined') {
alert('No file found on the location');
}
// do something with returned filename
});
</script>
which would try to check if the file is there, when not the previous index was the latest one. If the first one fails, there is no file on the specified location
This reply doesn't add formatting, and rather expects the files as:
- file-1.txt, file-2.txt, ...
this example assumes jquery :)
a fiddle of it you can find here
http://jsfiddle.net/Icepickle/JL5Su/

Categories

Resources