download file with blob in angular - javascript

im new to angular and i have to add a button to an app so when i click, it should start downloading a file already recorded.
i have this code
var _RecordStopCallback = function(blob){
if (!blob && blob.length==0){
$scope.isRecorded = false;
return;
}
$scope.recordObj.recordedData = blob;
const url = URL.createObjectURL(blob);
var el = $("#downloads").html("");
var hf = $("<a></a>");
hf.attr({
src:url,
href:url,
download:$scope.recordFilename
}).html($scope.recordFilename);
hf.appendTo(el);
$scope.isStoping = false;
$scope.recordStatus = false;
$scope.isRecorded = true;
$scope.recordStatusText = "Start";
$scope.streamError = "";
_changeStatusText();
$scope.$apply();
$scope.saveProcess();
and in the HTML file this:
<div ng-show="isRecorded" class="color-info"> Recorded File : <span id='downloads'></span>
<button ng-click="{{recordFilename}}" class="btn-circle btn-circle-default">
<i class="zmdi zmdi-download"></i></button>
this line:
<span id='downloads'></span>
displays the recoded filename and makes it as a link so when you click on it you can directly donwload it, but i dont know how to make the button do the same thing?
any help would be appreciated!

You may register a callback for the button getting clicked and there you can create the same link you showed in your question, style it as hidden, insert it into the DOM and call .click() on it.
Inserting into DOM is required as some browsers will not start the download otherwise.

Related

dynamically adding a button in html page with simple Javascript without any framework or library

hey there i'm making a simple webpage which requires to download an output image file at the last step..
but i don't know how can i add download button dynamically at correct time, because at starting of a page there is no need of download button..
so i have main.js file:
which looks something looks like this:
let img_code=document.getElementById('img_code');
let textbox=document.getElementById('textbox');
let gen_button_img=document.getElementById("img_button");
gen_button_qr.addEventListener("click",()=>
{
var trailer=textbox.value;
var url='www.example.com';
var result= url.concat(trailer);
if (navigator.onLine)
{
if(trailer.length<=1725 && trailer.length>0)
{
if((trailer !="0")&& (trailer.replace(/\s/g, '').length))
{
image_code.src=result;
alert("Image Generated successfully");
/**/
}
else
{
alert("You cannot create this file spaces only or only with single 0");
}
}
else
{
alert("Maximum charecter limit is exceeded!! ");
}
}
else
{
alert("No Internet Connection");
}
});
So, i have the question is there any way to dynamically add the button which takes file URL as input and download that file through web browser's downloader?
Note=>
I can easily save the result by right click on the picture and save image option; but i want to add an extra button to download the same file.
Most of the things explained in comments so read it first
// arrow function to create and append download button into any element
// it only takes url of file that will download.
const createBtn = (URL) => {
// create button element
const downloadBtn = document.createElement("button");
// you can set any name of id according to your choice
downloadBtn.setAttribute("id", "downloadBtn");
// create anchor element
const downloadLink = document.createElement("a");
// set any thing in inner text
downloadBtn.innerText = "Download Image";
// set download attribute to true
downloadLink.setAttribute("download", true);
// set url with URL
downloadLink.setAttribute("href", URL);
// append button element into anchor element
downloadLink.appendChild(downloadBtn);
// get that element in which download button will append
const container = document.getElementById("container");
// append download button into any element of your choice
container.appendChild(downloadLink);
};
// url of file
const URL = "https://images.pexels.com/photos/863963/pexels-photo-863963.jpeg?cs=srgb&dl=pexels-blaque-x-863963.jpg&fm=jpg"
// call createBtn function with URL
createBtn(URL);
<!-- The element in which download button will be appended -->
<div class="container" id="container"></div>
I am not 100% sure that this will work!
It also not work in stack snippet because iframe tag.
Try to use it locally.

Show/Hide button if iframe "src" contains certain text

I am trying to display a button if the src attribute of an iframe on the same page contains a certain text.
See jsFiddle for example.
I am basically trying to only show the "download MP3" button if the iframe has a valid soundcloud url as src attribute.
The one thing all valid soundcloud iframes have in common is: all src urls start with
//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F
You can get the dom element, and check it's src attribute.
Something like that:
const src = document.getElementById('ifrm').src;
if (src.indexOf('some')) {
console.log('YAY');
} else {
console.log('Not Yay')
}
<iframe src="https://some-site.com" id="ifrm" />
consider the following code snippet:
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var url = "//w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"
if(src.indexOf(url) !=-1){ //this will return -1 if false
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
or you can use regular expression test function :
var btn = document.getElementById("buttonId");//get the button
var src = document.getElementById("iframeId").src; // get the src
var patt = //"/w.soundcloud.com/player/?url=https%3A%2F%2Fsoundcloud.com%2F"/;
if(patt.test(src)){ // will return true if found
btn.style.display = "inline-block";//show the button
}else{
btn.style.display = "none";//hide the button
}
hope it helps

Uploading files using AJAX without FormData (IE9)

In IE9, FormData is not supported, which makes uploading files using XMLHttpRequest a lot less trivial.
Can this be done? I've seen iFrames mentioned, and while I'm not opposed to writing some hairy code, I'm at a loss as to how to achieve this (there are many resources talking about uploading to an iFrame but not about how to get the file from the iFrame to the server).
Using vanilla JavaScript (no third party libraries), how would one upload a file asynchronously without the use of FormData?
This code should do the trick. Sorry was a long time ago and I thought that IE9 also could upload using XHR (It should, but this is the Iframe option).
It does the following:
Add a file input to your page (can also be done in HTML)
Put that file selector in a form
add credentials to the form
Submit the form to the iframe and use its page as return value.
fileSelection = document.createElement("div");
//create the file input
fileSelection.browseSelect = document.createElement("input");
fileSelection.browseSelect.type = "file";
fileSelection.browseSelect.name = "file[]";
fileSelection.browseSelect.style.display = "block";
fileSelection.browseSelect.style.position = "absolute";
fileSelection.browseSelect.style.left = "50%";
fileSelection.browseSelect.style.top = "auto";
fileSelection.browseSelect.style.height = "36px";
fileSelection.browseSelect.style.width = "36px";
fileSelection.browseSelect.style.bottom = "0px";
fileSelection.browseSelect.style.margin = "0px 0px -1px 90px";
fileSelection.browseSelect.style.filter = "alpha(opacity=0)";
fileSelection.browseSelect.style.zIndex = 14;
//Put a form in it.
fileSelection.form = document.createElement("form");
fileSelection.form.method = "POST";
fileSelection.form.action = [url to server]; //put your own file upload handler here.
fileSelection.form.enctype = "multipart/form-data";
fileSelection.form.encoding = "multipart/form-data";
fileSelection.appendChild(fileSelection.form);
//Append the file input to the form.
fileSelection.form.appendChild(fileSelection.browseSelect);
document.body.appendChild(fileSelection);
function doUploadObjectUpload()
{
var tempFrame = document.createElement("iframe");
tempFrame.src = "";
tempFrame.allowTransparancy = "true";
tempFrame.style.display = "none";
tempFrame.frameBorder = 0;
tempFrame.style.backgroundColor = "transparent";
tempFrame.onload = followUpOnHTML4Upload.bind(this,tempFrame);
tempFrame.name = "tmpFrameUpload"
this.appendChild(tempFrame);
this.form.target = tempFrame.name;
this.form.name = "uploadForm";
this.form.acceptCharset = "UTF-8"
//This is an example of a hidden input, used to pass extra vars to the server. Add more if you need them.
var tempNodePath = document.createElement("input");
tempNodePath.type = "hidden";
tempNodePath.value = [dir]; //if you want specify a target path.
tempNodePath.name = "filePath";
this.form.insertBefore(tempNodePath, this.form.childNodes[0]);
this.form.submit();
}
function followUpOnHTML4Upload(frameId)
{
//Here you can check the response that came back from the page.
}
PHP for example will store the files in $_FILES

window.open not working with Google Chrome?

I'm trying to open 2 pages with one click of a link, and this is what I have so far:
<a onclick="download()" href="?event=thanks&dl=<?php echo $_GET['dl']; ?>"><?php echo $linkname ?></a>
and the Javascript function:
function download() {
newwindow=window.open('http://www.google.com','download','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
The code above works perfectly with FireFox and Safari, but it fails to open a new window with Google Chrome. Why is this? My thanks to anyone who can help.
<a> elements have a download attribute in HTML5 as explained here, with a default value of "" (an empty string).
This means that download === this.download in the onclick handler (this is the element in onevent attributes), and therefore the download attribute of the element is superior to the download property of window.
Oh, what a nightmare. Your function should not named download(). Change your function name to download1() and change your onclick to download1() too
You can use HTML5 download attribute.This attribute will tell browser that virtual link we created is aimed for download only. It will download file from links href to file with name specified as download attributes value. This feature works with Chrome.
Sample Code:
window.downloadFile = function(sUrl) {
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined){
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click' ,true ,true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
var query = '?download';
window.open(sUrl + query);
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;

How to load HTML file into <editor>

I'm trying to figure out how to get my XUL app to open an HTML file and load it into an editor element. However, documentation is sparse.
Right now, I have a content window like so:
<hbox id="main-frame" flex="1">
<tabbox id="workspace-tabbox" flex="1">
<tabs id="workspace-tabs"/>
<tabpanels id="workspace-tabpanels" flex="1" context="clipmenu"/>
</tabbox>
<splitter id="main-frame-splitter"/>
<iframe id="preview-frame" src="about:blank" flex="1"/>
</hbox>
With javascript I append a <tab> to the <tabs>, and a <tabpanel> to the <tabpanels>. I then create an <editor>, append it to the <tabpanel>, and make it editable.
Then, there is an Open button linked to this function:
function promptFile() {
var filepicker = Components.classes["#mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
var file;
var choice;
var path = null;
filepicker.init(window, "Open", filepicker.modeOpen);
filepicker.appendFilters(filepicker.filterHTML);
choice = filepicker.show();
if (choice == filepicker.returnOK) {
file = filepicker.file.QueryInterface(Components.interfaces.nsIFile);
path = file.path;
}
return path;
}
From here, I don't know how to load it into the <editor>. I'm also not sure if I'm on the right path getting the 'path', or if I need to do something with the 'file' object, instead.
Any insight or help on this would be greatly appreciated.
An <editor> is essentially a frame - you simply need to load the correct URL into that frame. You can use nsIIOService.newFileURI to get that URL from an nsIFile instance:
Components.utils.import("resource://gre/modules/Services.jsm");
var uri = Services.io.newFileURI(file);
var editor = document.getElementById("editor");
var loadFlags = Components.interfaces.nsIWebNavigation.LOAD_FLAGS_NONE;
editor.webNavigation.loadURI(uri.spec, loadFlags, null, null, null);
editor.makeEditable("html", true);
For reference: nsIWebNavigation.loadURI

Categories