Hi i have a problem i was using usbwebserver for my localhost but i had to switch to xampp because of php 5.5. But now is one of my functions misbehaving. It shows only 2/6 pictures from directory and i don't know why. It's function that will add an image to my body when clicked on that image. No errors on page found.
var pom = document.getElementById("ImageAdd");
pom.style.visibility = "visible";
var dir = "uploads";
var fileextension = [".png", ".jpeg", ".jpg", ".gif"];
$.ajax({
url: dir,
success: function(data) {
for (var i = 0; i < fileextension.length; i++) {
$(data).find("a:contains(" + fileextension[i] + ")").each(function() {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("#ImageAdd").append("<img src=\"" + dir + filename + "\" onclick=\"addimg('" + dir + filename + "')\">");
});
}
}
});
Related
Any help is greatly appreciated! I've spent so long searching but I haven't found a solution or a problem like mine...
I'm writing an Electron application, and as part of it, there is a section for the users to drag and drop files. I'm then taking that file and uploading it to AWS S3.
The first time I drag and drop it goes into my function but no request is sent out to AWS S3, I then drag and drop again and it sends out the expected request and saves the file however it's the first requests information (name, path & body), and from then on when I drag and drop the file it send outs the request every time but always with the previous request's info. It's like its one sequence behind....
This is the s3 code:
function submitNewFileS3(file, filepath) {
const AWS = require('aws-sdk');
AWS.config = new AWS.Config({
accessKeyId: localStorage.getItem("accessKeyId"),
secretAccessKey: localStorage.getItem("secretAccessKey"),
region: 'eu-west-2'
});
var upload = new AWS.S3.ManagedUpload({
params: {
Bucket: 'sampe-bucket',
Key: filepath, // File name you want to save as in S3
Body: file
}
});
return upload.promise();
}
How I call the function:
var reader = new FileReader();
reader.onload = function (e2) {
// finished reading file data.
finishUploading(e2.target.result);
}
function finishUploading(url) {
// strip off the data: url prefix to get just the base64-encoded bytes
var data;
if (url.indexOf('data:image') > -1) {
data = url.replace(/^data:image\/\w+;base64,/, "");
} else if (url.indexOf('data:application') > -1) {
data = url.replace(/^data:application\/\w+;base64,/, "");
}
//only firing after sencon upload
var buf = Buffer.from(data, 'base64');
var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
submitNewFileS3(buf, filePathS3).then(function (response) {
console.log(response);
}).catch(function (response) {
console.log(response);
});
}
reader.readAsDataURL(f); // start reading the file data.
Does anyone have any suggestions - I'm going out of my mind...I've tried so many tutorials and solutions and they all work...on the second call...
I've double checked all the required data is ready before making the request.
Many thanks in advance!
EDIT - more of what's going on in my main before sending my file to be uploaded:
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
var directory;
if (e.target.id == 'drop_zone_overview') {
//placed in general area, check which folders are showing to get dir
console.log(e);
//get whats visible
var whatPath;
$(".icon").each(function () {
if (this.style.display != 'none') {
whatPath = this.id;
}
});
//pick one and check what root we're in
var pathArray = whatPath.split('-');
console.log(pathArray);
} else if (e.target.id == 'drop_zone_individual') {
//placed on top of folder, check dir
directory = (e.target).getAttribute('data-targetfolder');
console.log(directory);
}
var files = e.dataTransfer.files,
folder;
for (var i = 0, f; f = files[i]; i++) { // iterate in the files dropped
if (!f.type && f.size % 4096 == 0) {
// The file is a folder
folder = true;
} else {
// The file is not a folder
folder = false;
}
const fs = require('fs');
console.log(f);
var fileName = f.name;
var reader = new FileReader();
reader.onload = function (e2) {
// finished reading file data.
finishUploading(e2.target.result);
}
function finishUploading(url) {
// strip off the data: url prefix to get just the base64-encoded bytes
var data;
if (url.indexOf('data:image') > -1) {
data = url.replace(/^data:image\/\w+;base64,/, "");
} else if (url.indexOf('data:application') > -1) {
data = url.replace(/^data:application\/\w+;base64,/, "");
}
var buf = Buffer.from(data, 'base64');
var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
submitNewFileS3(buf, filePathS3).then(function (response) {
console.log(response);
}).catch(function (response) {
console.log(response);
});
}
reader.readAsDataURL(f); // start reading the file data.
uploadedFiles.push(f);
}
uploadedFiles.forEach(function (file) {
var pathKey = directory + (file.name).replace(/\-/g, "_");
pathKey = pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__');
if ($('#' + pathKey).length) {
//filename already exists in directory
alert(file.name + ' already exists in folder ' + directory);
} else {
var displayDiv;
if (file.type == 'image/png') {
//image
//add to directory
displayDiv = '<img id="' + pathKey + '" class="fileInfo thumb file-type file-type-img" src="' + URL.createObjectURL(file) + '" ondblclick="preview_image(this)"/>'
} else if (file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
//xlsx doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-xlsx" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';
} else if (file.type == 'application/pdf') {
//pdf doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-pdf" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';
} else if (file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
//word doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-docx" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';
console.log('its a doc');
} else if (file.type == 'application/x-zip-compressed') {
//zip file doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-zip" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';
} else if (file.type == '') {
//folder
console.log('what typep is this~~~~~ ' + file.type);
file.name = file.name + '/';
}
//save to folder array
if (file.type == 'application/x-zip-compressed' || file.type == '') {
var htmlTemplate = [
getHtml([
'<li id=' + pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__') + ' class="icon folderItems fileInfo thumb" data-downloadLink="directory_' + pathKey + '" ondblclick="viewAlbum(this.id)" style="display:none">',
'<i id="drop_zone_individual" data-targetFolder="' + pathKey + '" class="folders fas fa-folder" style="font-size: 115px; color: rgb(13, 36, 60); cursor: pointer;"></i>',
'<div class="folderLabel" style="text-align:center">' + file.name + '</div>',
'</li>'
])
];
folders.push({
Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
LastModified: file.lastModifiedDate,
Size: file.size,
});
} else {
//append to ui file list
var htmlTemplate = [
getHtml([
'<li id=' + pathKey + ' class="icon downloadableItem" style="display:none">',
'<span>',
'<div style="text-align:center">',
displayDiv,
'</div>',
'<div style="text-align:center">',
'<span>',
file.name,
'</span>',
'</div>',
'</span>',
'</li>'
])
];
//save to folder list
folders.push({
Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
LastModified: file.lastModifiedDate,
Size: file.size,
signedUrl: URL.createObjectURL(file)
});
}
localStorage.setItem("s3Objects", JSON.stringify(folders));
$('#photoAlbumViewerList').append(htmlTemplate);
console.log(folders);
$("#" + pathKey).click(function (e) {
getAlbumInfo(this.id);
if (e.shiftKey) {
if ($(this).hasClass('thumb')) {
$(this).removeClass('thumb').addClass('thumbChecked');
$(this).css("border", "2px solid #c32032");
// $(this).attr("data-downloadLink");
links.push($(this).attr("data-downloadLink"));
if (links.length != 0) {
$('.download').css("display", "block");
}
} else if ($(this).hasClass('thumbChecked')) {
$(this).removeClass('thumbChecked').addClass('thumb');
$(this).css("border", "2px solid white");
var itemtoRemove = $(this).attr('src');
links.splice($.inArray(itemtoRemove, links), 1);
console.log(links);
if (links.length == 0) {
$('.download').css("display", "none");
}
}
}
});
}
});
uploadedFiles = [];
e.target.classList.remove('drop_zone_hovered');
$('#drop_zone_text').hide();
}
As an FYI - the issue lied where I reinitialised AWS and S3 variables, it wasn't needed as I set it at the start of launch and reinitialising it slowed it all down while it remade the connection!
I have tried to upload images with ckeditor but my problem is that the images upload to the server folders but ddoesnt show in my ckeditor text area , it show server response error , any help please ?
This is my code :
router.post('/upload&responseType=json', function(req, res) {
var fs = require('fs');
var tmpPath = req.files.upload.name;
l = tmpPath.split('/').length;`enter code here`
var fileName = tmpPath.split('/')[l - 1] + "_" + "s";
var buf = new Buffer.from(req.files["upload"].data);
var newPath ='public/uploads/'+tmpPath;
console.log(newPath);
console.log(tmpPath);
console.log(fileName);
fs.writeFile(newPath,buf, function (err) {
if (err) console.log({err: err});
else {
html = "uploaded";
html += "<script type='text/javascript'>";
html += " var funcNum = " + req.query.CKEditorFuncNum + ";";
html += " var url = \"/uploads/" + fileName;
html += " var message = \"Uploaded file successfully\";";
html += "";
html += " window.parent.CKEDITOR.tools.callFunction(funcNum, url, message);";
html += "</script>";
res.send(html);
}
});
});
This is my ckeditor
CKEDITOR.config.customConfig = '/js/ckeditor_config.js';
CKEDITOR.replace(editor2,{ filebrowserUploadUrl: '/upload', });
And this my ckeditor config file :
CKEDITOR.editorConfig = function( config )
{
config.filebrowserUploadMethod = 'form';
config.toolbar = 'MyToolbar';
config.toolbar_MyToolbar =
[
['Source','Templates'],
['Cut','Copy','Paste','SpellChecker','-','Scayt'],
['Undo','Redo','-','Find','Replace'],
['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
['Maximize','-','About'],
'/',
['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','SelectAll','RemoveFormat'],
['Link','Unlink','Anchor'],
['Styles','Format','Font','FontSize'],
['TextColor','BGColor']
];
};
You do not have to send the whole HTML in the newer versions of ckeditor..
You are just supposed to send the URL as shown below:
res.send({
url: "<SERVER_URL>/public/uploads/" + fileName,
})
If you are working on localhost
replace SERVER_URL with something like http://localhost:3000
Another thing, you have to set
app.use(express.static('public/uploads'));
If you want to access the image using the URL mentioned above.
I need to build a gallery in HTML and load images from a local directory.
I can't use PHP, only JavaScript, HTML, and CSS.
This is my code so far, but it is not working.
$(document).ready(function() {
var dir = "G:\\Arml\\Automation\\System\\Pic\\test\\"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop() {
$("<img />").attr('src', dir + i + fileextension).appendTo(".testing");
if (i == 10) {
alert('loaded');
} else {
i++;
imageloop();
};
});
});
1-Could you try to change the variable dir by another name witch could be used by another javascript library
2- give the img width and height like this for example:
$("<img width='100' height='50' />").attr('src', dir + i + fileextension ).appendTo(".testing");
this is the javaScript was work:
$(document).ready(function(){
var dir = "path"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
$('.gallary').prepend('<li><img id="' + i + '" alt="description" /><img id="1' + i + '" alt="description" class="preview" /></li>')
if (i==11){
}
else{
$("#"+i).attr('src', dir + i + fileextension );
$("#1"+i).attr('src', dir + i + fileextension );
i++;
imageloop();
};
});
});
When I try push some element to array and display random element, browser return that array is not define. Where is problem?
var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + ext + ")").each(function () {
var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
slike.push(dir + ime_slike + ext);
});
}
});
$('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
AJAX is Asynchronous. The code that populates your array is being called after the code that uses the array. Move the code that creates the image into the success handler:
var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + ext + ")").each(function () {
var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
slike.push(dir + ime_slike + ext);
});
if (slike.length) {
$('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
}
}
});
i am a newbie with jquery and i was playing with this plugin. i am using it with asp.net and I want to get number of file dropped in it. I tried a bit but failed to get. Any idea?
Here is the code of script.js:
$(function () {
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname: 'pic',
maxfiles: 100,
maxfilesize: 100,
//url: '/Uploader.asmx/Upload',
url: '/Default.aspx',
uploadFinished: function (i, file, response) {
$.data(file).addClass('done');
var count = file.size;
alert(count);
},
error: function (err, file) {
switch (err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 5 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name + ' is too large! Please upload files up to 2mb (configurable).');
break;
default:
break;
}
},
//Called before each upload is started
// beforeEach: function (file) {
//if (!file.type.match(/^image\//)) {
//alert('Only images are allowed!');
// alert(file.name);
// Returning false will cause the
// file to be rejected
// return true;
// }
//},
uploadStarted: function (i, file, len) {
createImage(file);
},
progressUpdated: function (i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">' +
'<span class="imageHolder">' +
'<img style="" />' +
'<p class="background: rgba(0, 0, 0, 0.75);"></p>' +
'<span class="uploaded"></span>' + // background: rgba(0, 0, 0, 0.75);
'</span>' +
'<div class="progressHolder">' +
'<div class="progress"></div>' +
'</div>' +
'</div>';
function createImage(file) {
var preview = $(template),
image = $('img', preview),
paragraph = $('p', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function (e) {
// e.target.result holds the DataURL which
// can be used as a source of the image:
//alert(e.target.result);
// $('p#filename').removeAttr('id');
// $('p').attr('id', 'filename' + num + '');
// $('p#filename').text(file.name);
paragraph.attr('id', 'filename').text(file.name);
image.attr('src', '../assets/img/fileicon.png');
num = num + 1;
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's $.data():
$.data(file, preview);
}
function showMessage(msg) {
message.html(msg);
}
});
It's in the input element. I had a fiddle that uses it in a change event, in which case it's in event.target.files.
edit: should include the fiddle: http://jsfiddle.net/jorgthuijls/uh95y/3/ try it by attaching PDF's.
The relevant code here. This loops over the files and creates "preview" boxes for PDF's but you can just count it as well. files below is an array.
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.addEventListener("load", function (event) {
//stick some rubbish here to check the type of
//file loaded and adjust "type" below. See the
// 'reader' object, it has all that.
var div = document.createElement("div");
div.innerHTML
= '<object data="'
+ reader.result
+ '" type="application/pdf">'
+ '<embed src="'
+ reader.result
+ '" type="application/pdf" />'
+ '</object>';
output.insertBefore(div, null);
});
//Read the image
reader.readAsDataURL(file);
}
});