Changing default file name download with JS? - javascript

How would I go about changing the name of a clip that is going to be downloaded by the client on a website? Each video clip currently downloaded is a default name how do I go about customising it?
Below is the function for the download button.
// Function to generate the Download button
VideoPlayer.prototype.initDownload = function () {
var downloadBtn = $("button.download"),
downloadToolTipCls = "download_tooltip",
sources = {},
downloadToopTip,
sourcesLength = 0,
sourcesKeys;
// Add each source
if (typeof (firstSrc = this.$video.attr("src")) !== "undefined") {
sources[firstSrc] = this.$video.attr("type");
}
this.$video.find("source").each(function () {
var $this = $(this);
sources[$this.attr("src")] = $this.attr("type");
});
sourcesKeys = Object.keys(sources);
sourcesLength = sourcesKeys.length;
if (sourcesLength === 1) {
downloadBtn.wrap("<a href=\"" + sourcesKeys[0] + "\" download />");
} else if (sourcesLength > 1) {
downloadBtn.after("<span class=\"" + downloadToolTipCls + "\" />");
downloadToopTip = $("." + downloadToolTipCls);
$.each(sources, function (source, type) {
downloadToopTip.append("<a href=\"" + source + "\" download> Type " + type + "</a>");
});
downloadBtn.click(function () {
downloadToopTip.toggle();
});
}
};

Put the name that you want for your file in download attribute download=name

Related

Have to wait for the second file upload request for the first one's data to send to AWS S3

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!

jQuery to emulate iPhone password input changes textbox to disabled in a Visual Studio web application

I am working on a web application in Visual Studio using visual basic and master pages. I have 10 textbox fields on a child page where I would like to emulate the iPhone password entry (ie. show the character entered for a short period of time then change that character to a bullet). This is the definition of one of the text box controls:
<asp:TextBox ID="txtMID01" runat="server" Width="200" MaxLength="9"></asp:TextBox>
At the bottom of the page where the above control is defined, I have the following:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="lib/jQuery.dPassword.js"></script>
<script type="text/javascript">
$(function () {
var textbox01 = $("[id$=txtMID01]");
alert(textbox01.attr("id"));
$("[id$=txtMID01]").dPassword()
});
</script>
When the page loads, the alert displays MainContent_txtMID01 which is the ID of the control preceeded with the name of the content place holder.
The following is the contents of lib/jQuery.dPassword.js (which I found on the internet):
(function ($) {
$.fn.dPassword = function (options) {
var defaults = {
interval: 200,
duration: 3000,
replacement: '%u25CF',
// prefix: 'password_',
prefix: 'MainContent_',
debug: false
}
var opts = $.extend(defaults, options);
var checker = new Array();
var timer = new Array();
$(this).each(function () {
if (opts.debug) console.log('init [' + $(this).attr('id') + ']');
// get original password tag values
var name = $(this).attr('name');
var id = $(this).attr('id');
var cssclass = $(this).attr('class');
var style = $(this).attr('style');
var size = $(this).attr('size');
var maxlength = $(this).attr('maxlength');
var disabled = $(this).attr('disabled');
var tabindex = $(this).attr('tabindex');
var accesskey = $(this).attr('accesskey');
var value = $(this).attr('value');
// set timers
checker.push(id);
timer.push(id);
// hide field
$(this).hide();
// add debug span
if (opts.debug) {
$(this).after('<span id="debug_' + opts.prefix + name + '" style="color: #f00;"></span>');
}
// add new text field
$(this).after(' <input name="' + (opts.prefix + name) + '" ' +
'id="' + (opts.prefix + id) + '" ' +
'type="text" ' +
'value="' + value + '" ' +
(cssclass != '' ? 'class="' + cssclass + '"' : '') +
(style != '' ? 'style="' + style + '"' : '') +
(size != '' ? 'size="' + size + '"' : '') +
(maxlength != -1 ? 'maxlength="' + maxlength + '"' : '') +
// (disabled != '' ? 'disabled="' + disabled + '"' : '') +
(tabindex != '' ? 'tabindex="' + tabindex + '"' : '') +
(accesskey != undefined ? 'accesskey="' + accesskey + '"' : '') +
'autocomplete="off" />');
// change label
$('label[for=' + id + ']').attr('for', opts.prefix + id);
// disable tabindex
$(this).attr('tabindex', '');
// disable accesskey
$(this).attr('accesskey', '');
// bind event
$('#' + opts.prefix + id).bind('focus', function (event) {
if (opts.debug) console.log('event: focus [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
checker[getId($(this).attr('id'))] = setTimeout("check('" + getId($(this).attr('id')) + "', '')", opts.interval);
});
$('#' + opts.prefix + id).bind('blur', function (event) {
if (opts.debug) console.log('event: blur [' + getId($(this).attr('id')) + ']');
clearTimeout(checker[getId($(this).attr('id'))]);
});
setTimeout("check('" + id + "', '', true);", opts.interval);
});
getId = function (id) {
var pattern = opts.prefix + '(.*)';
var regex = new RegExp(pattern);
regex.exec(id);
id = RegExp.$1;
return id;
}
setPassword = function (id, str) {
if (opts.debug) console.log('setPassword: [' + id + ']');
var tmp = '';
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == unescape(opts.replacement)) {
tmp = tmp + $('#' + id).val().charAt(i);
}
else {
tmp = tmp + str.charAt(i);
}
}
$('#' + id).val(tmp);
}
check = function (id, oldValue, initialCall) {
if (opts.debug) console.log('check: [' + id + ']');
var bullets = $('#' + opts.prefix + id).val();
if (oldValue != bullets) {
setPassword(id, bullets);
if (bullets.length > 1) {
var tmp = '';
for (i = 0; i < bullets.length - 1; i++) {
tmp = tmp + unescape(opts.replacement);
}
tmp = tmp + bullets.charAt(bullets.length - 1);
$('#' + opts.prefix + id).val(tmp);
}
else {
}
clearTimeout(timer[id]);
timer[id] = setTimeout("convertLastChar('" + id + "')", opts.duration);
}
if (opts.debug) {
$('#debug_' + opts.prefix + id).text($('#' + id).val());
}
if (!initialCall) {
checker[id] = setTimeout("check('" + id + "', '" + $('#' + opts.prefix + id).val() + "', false)", opts.interval);
}
}
convertLastChar = function (id) {
if ($('#' + opts.prefix + id).val() != '') {
var tmp = '';
for (i = 0; i < $('#' + opts.prefix + id).val().length; i++) {
tmp = tmp + unescape(opts.replacement);
}
$('#' + opts.prefix + id).val(tmp);
}
}
};
})(jQuery);
When I execute my code, the code behind populates the value of the textbox with "123456789" and when the page gets rendered, all the characters have been changed to bullets, which is correct. The problem I am having is that the textbox has been disabled so I can not edit the data in the textbox.
I removed (by commenting out) the references to the disabled attribute but the control still gets rendered as disabled.
As a side note, the code that I found on the internet was originally designed to work with a textbox with a type of password but when I set the TextMode to password, not only does the control get rendered as disabled, but the field gets rendered with no value so I left the TextMode as SingleLine.
Any suggestions or assistance is greatly appreciated.
Thanks!
As far as I know, it is not possible to have it so that while you type a password, the last letter is visible for a second and then turns into a bullet or star.
However what you can do is as the user types in password, with a delay of lets say 500ms store the string the user has typed in so far into some variable and replace the content of the password field or the text field with stars or black bullets. This will give you what you are looking for.

load image automtacily to html page withe javascript(not php)

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();
};
});
});

Showing loading indication while loading XML

I have a webpage that I load my data from XML files to DIVs.
In this Example I have DIV with this attribute: class="Group";
Also this is my JS code:
$(document).ready(function () {
$.get(Root + "/Feed_Products/Groups", {}, function (xml) {
var output = '';
$('item', xml).each(function (i) {
var Name = $(this).find("Name").text();
var Id = $(this).find("Id").text();
var Link = Root + '/Group' + Id;
output += '' + Name + '';
});
$(".Group").append(output);
});
});
As you know, loading XML has delay and its not as fast as direct database request.
How can I show small loading GIF on each DIV that is loading XML?
Image: http://i.stack.imgur.com/BPWcg.png
$(document).ready(function () {
$(".Group").addClass("loading");
$.get(Root + "/Feed_Products/Groups", {}, function (xml) {
var output = '';
$('item', xml).each(function (i) {
var Name = $(this).find("Name").text();
var Id = $(this).find("Id").text();
var Link = Root + '/Group' + Id;
output += '' + Name + '';
});
$(".Group").append(output).removeClass("loading");
});
});
Then in your css define :
.Group.loading{
background-image: url("yourGIF.gif");
/* other rules */
}

HTML read javascript and put result into a div

I'm new to HTML/javascript and I want to make something that displays Last.FM current playing songs, into a div on html, which displays it in text, I have a code that sends the current song through a chat on www.irccloud.com, and I was wondering If you could change it so that It could get received and put into a DIV on a page, the code is below:
and var r is the completed code, so how would I do something in the div that picks up the source as the link above and then grabs var r from it? If so, how would I do it??
I have tried the following code here
Sorry if I do not make sense.
(function () {
var e = "DeviousRunner";
window.lfmRecentTrack = function (t) {
var n = (new Array).concat(t.recenttracks.track)[0];
var album, spurl;
if (n.album["#text"]) {
album = " (from " + n.album["#text"] + ")";
} else {
album = "";
}
try {
var spotify = new XMLHttpRequest();
spotify.open("GET", "https://ws.spotify.com/search/1/track.json?q=" + encodeURIComponent(n.artist["#text"] + " - " + n.name), false);
spotify.send();
var spotresp = JSON.parse(spotify.responseText);
if (spotresp["tracks"].length > 0) {
//var urisplit = spotresp["tracks"][0]["href"].split(":");
//spurl = " https://open.spotify.com/" + urisplit[1] + "/" + urisplit[2];
spurl = spotresp["tracks"][0]["href"];
} else {
console.log("spotify: couldn't get url");
spurl = "";
}
} catch(e) {
console.log("spotify: " + e.message);
spurl = "";
}
var r = "is listening to " + n.name + " by " + n.artist["#text"] + " " + album + " (" + spurl + ")";
}
var n = document.createElement("script");
n.setAttribute("type", "text/javascript");
n.setAttribute("src", "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=" + e + "&api_key=dd5fb083b94a7196cf696b9d7d11bc63&limit=1&format=json&callback=window.lfmRecentTrack");
document.body.appendChild(n)
})();
I updated your FIDDLE,
by moving this:
var element = document.getElementById("rss");
element.innerHTML = r;
inside the function...
hope this is useful for you

Categories

Resources