How to create and download file from angular app? Issue with blob - json

I can't download my generated file from app. Code now looks like this:
async handleFileTranslateAction(): Promise<void> {
this.progressSpinerIsVisible = true
this.originLanguageSelect = await this.languageService.getById(this.selectedOriginLanguage).toPromise()
this.destinationLanguageSelect = await this.languageService.getById(this.selectedDestinationLanguage).toPromise()
const result = await this.translateService.getTranslatedJson(
this.fileInput.getFile(),
this.originLanguageSelect,
this.destinationLanguageSelect
)
const result2 = JSON.stringify(result)
console.log(result2)
const blob = new Blob([result2], { type: 'text/json' });
console.log(blob)
this.fileDownloadUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
// const blob = new Blob([result2], { type: 'text/json' });
// const url= window.URL.createObjectURL(blob);
// window.open(url);
const element: HTMLElement = document.getElementById('download-final-json-button') as HTMLElement;
element.click()
this.progressSpinerIsVisible = false
}
When i consol loging result2, everything showing up correctly, all data is fine, but when i try console log blob and even, when i download a file, i always recieving file contains only this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TachoTranslations</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght#300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<tt-root></tt-root>
<script src="runtime.js" defer></script><script src="polyfills.js" defer></script><script src="styles.js" defer></script><script src="vendor.js" defer></script><script src="main.js" defer></script></body>
</html>
The commented section don't works for me. I just want to download json file.

you can try with
blob = new Blob([response], { type: 'text/json' });
const url = window.URL.createObjectURL(blob);
window.open(url);
edit.
something like this?
downloadFromLocal(path) {
let link = document.createElement('a');
link.setAttribute('type', 'hidden');
link.href = `${path}`; //path to the file
link.download = 'autocertificazione.docx';// name that the file takes
document.body.appendChild(link);
link.click();
link.remove();
}

Related

How to upload a File to Firebase using HTML and store user details with link in DATABASE

I have a website in which I want to add a file upload option so how to do it using firebase in HTML
and I also want to collect user details while uploading files like users entering details and storing them in the database. How to do it.
I am a beginner in programming that's why I am asking please help me who knows the answer if possible please provide the code
The code which I have tried :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
Upload Files<br />
<input type="file" id="files" multiple /><br /><br />
<button id="send">Upload</button>
<p id="uploading"></p>
<progress value="0" max="100" id="progress"></progress>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "******************",
authDomain: "******************",
projectId: ******************,
storageBucket: ******************,
messagingSenderId: "******************",
appId: "******************",
measurementId: "******************"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script>
var files = [];
document.getElementById("files").addEventListener("change", function(e) {
files = e.target.files;
for (let i = 0; i < files.length; i++) {
console.log(files[i]);
}
});
document.getElementById("send").addEventListener("click", function() {
//checks if files are selected
if (files.length != 0) {
//Loops through all the selected files
for (let i = 0; i < files.length; i++) {
//create a storage reference
var storage = firebase.storage().ref(files[i].name);
//upload file
var upload = storage.put(files[i]);
//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("progress").value = percentage;
},
function error() {
alert("error uploading file");
},
function complete() {
document.getElementById(
"uploading"
).innerHTML += `${files[i].name} upoaded <br />`;
}
);
}
} else {
alert("No file chosen");
}
});
function getFileUrl(filename) {
//create a storage reference
var storage = firebase.storage().ref(filename);
//get file url
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
}
</script>
</body>
</html>

How do I load extension when viewing local file

I am using the example taken from viewer-javascsript-offline.sample
I have an extension that was created using nodejs tutorial (link) that I got it working using the tutorial code to register the extension. However, when I tried the same thing using the offline viewer code sample (using viewer3D instead of viewingApplication), I am not able to view the extension's button.
note: I can guarantee that the handleselectionextension.js is working fine as I've got it working in the tutorial version.
codes:
index.css and index.html
.handleSelectionToolbarButton {
background-image: url(https://github.com/encharm/Font-Awesome-SVG-PNG/raw/master/white/png/24/object-group.png);
background-size: 24px;
background-repeat: no-repeat;
background-position: center;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Very Basic 3D Viewer</title>
<link rel="stylesheet" href="https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css?v=4.2.*" type="text/css">
<link href="index.css" rel="stylesheet" />
</head>
<body>
<div id="MyViewerDiv"></div>
<!-- The Viewer JS -->
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/three.min.js?v=4.2.*"></script>
<script src="https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js?v=4.2.*"></script>
<script src="handleselectionextension.js"></script>
<!-- Developer JS -->
<script>
var myViewerDiv = document.getElementById('MyViewerDiv');
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv);
var options = {
'env': 'Local',
'document': "0/1/Design.svf",
'extensions': ["HandleSelectionExtension"]
};
Autodesk.Viewing.Initializer(options, function() {
viewer.start(options.document, options);
});
</script>
</body>
</html>
The extension config is not for Initializer, you have to pass it to 2nd argument of the viewer constructor like this:
var config3d = {
'extensions': ["HandleSelectionExtension"]
};
var myViewerDiv = document.getElementById('MyViewerDiv');
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv, config3d);
var options = {
'env': 'Local',
'document': "0/1/Design.svf"
};
Autodesk.Viewing.Initializer(options, function() {
viewer.start(options.document, options);
});

How to Fetch multiple images in nodeJS?

So, problem is i have two jpg images you can see in HTML code. But only download.jpg is showing not lenovo.jpg but both are showing in the req.url
console image is attached and output is also attached.
HTML output
Console ScreenShot
this is my js file
//creating web server
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function(req,res){
if(req.url === "/"){
fs.readFile('./public/index.html',"UTF-8", function(err,html){
res.writeHead(200,{'content-type': 'text/html'});
res.end(html);
});
}
else if(req.url.match("\.css$")){
var cssPath = path.join(__dirname, '/public', req.url);
var fileStream = fs.createReadStream(cssPath, "UTF-8");
res.writeHead(200, {'content-type': 'text/css'});
fileStream.pipe(res);
}
else if(req.url.match("\.jpg$")){
var imagePath = path.join(__dirname,'/public',req.url);
var fileStream = fs.createReadStream(imagePath);
res.writeHead(200,{'content-type': 'image/jpg'});
fileStream.pipe(res);
}
console.log(req.url);
}).listen(3000);
My Html
<!DOCTYPE html>
<html>
<head>
<!-- <meta charset="utf-8"> -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My HTML Page</title>
<link rel="stylesheet" type="text/css" href="./css/base.css">
</head>
<body>
<h1> My First Heading From the Page of html </h1>
<img src="./images/download.jpg">
<img src="./images/lenovo.jpg">
</body>
</html>
Look at size of your lenovo.jpg image it have very high resolution please use low resolution or define width and height in img tag.
If you don't have a strict requirement not to use express, I suggest you to use express, and you can handle it with express' static file handling method:
https://expressjs.com/en/starter/static-files.html

Adding same button to each item on list?

I have a task list where I want to add the "hide button" to each item on the list. I have one and every time you click it, it hides the entire list. I want to be able to have a button for each item and only hide that certain item once clicked. I have the fiddle here: https://jsfiddle.net/9cp9twfh/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="asana.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Asana</title>
</head>
<body>
<div class="topnav" id="myTopnav">
</div>
<button class="button">Hide Task</button>
<div class="task-list"></div>
<script src="asana.js"></script>
</body>
</html>
$(document).ready(function(){
$.ajax({
method: 'GET',
url: 'https://app.asana.com/api/1.0/projects/507623085822462/tasks',
headers: {
'Authorization': 'Bearer 0/0c60e78596a717c771c04c1c35b0a451'
},
success: function(result) {
$('.card').find('.taskname').html(result.data.name);
showTaskList(result.data);
}
});
});
$(document).ready(function() {
$('button').click(function() {
$('.task-list').stop(true).toggle('slow');
$('.button').text(function(i, t) {
return t == 'Show Task' ? 'Hide Task' : 'Show Task';
});
});
});
var showTaskList = function(taskList) {
for(var i = 0; i < taskList.length; i++) {
showTask(taskList[i]);
}
};
var showTask = function(taskData){
var taskList = $('.task-list');
var card = $('<div></div>').addClass('card');
var taskName = $('<div></div>').addClass('taskname');
taskName.html(taskData.name);
card.append(taskName);
taskList.append(card);
};
var showTask = function(taskData){
...
card.append(taskName);
card.append("<button class='hide' type='button'>Hide</button>");
taskList.append(card);
}
$(".task-list").on("click", "button.hide", function(){
$(this).closest(".card").hide();
});

JSonRestStore and CLientfilter

I've setup a little script for testing JRS and a clientfilter. I've used what I could find on the internet to set it up but it ain't working. I'm trying to perform a client side fetch on a JRS using clientFilter. Nevertheless the JRS is querying the backend in stead of performing the fetch clientsided. I pasted the script below, I hope one of you can explain why it isn't working.
Thanks
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="js/dojo-release-1.7.2/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="js/dojo-release-1.7.2/dijit/themes/tundra/tundra.css"/>
<script>
dojoConfig= {
has: {
"dojo-firebug": true
},
parseOnLoad: true,
isDebug: true,
locale: "nl"
};
</script>
<script type="text/javascript" src="js/dojo-release-1.7.2/dojo/dojo.js"></script>
<script type="text/javascript">
dojo.require("dojox.data.ClientFilter");
dojo.require("dojox.data.JsonRestStore");
dojo.require("dijit.form.Button");
myStore = new dojox.data.JsonRestStore({target:"TARGET"});
myStore.fetch();
dojo.ready(function() {
dojo.connect(dijit.byId("query"), "onClick", function() {
myStore.fetch({query:{id:"4"},queryOptions:{cache:true}, onItem: function(item) {console.log(item); }});
});
});
</script>
</head>
<body cllass="tundra">
<button type="button" id="query" data-dojo-type="dijit.form.Button">Query</button>
</body>
I made a jsfiddle that shows how to do this with the new syntax and dojo stores.
http://jsfiddle.net/SgyYW/
require([
"dojo/store/Cache",
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/parser",
"dojo/on",
"dojo/ready",
"dijit/form/Button",
"dijit/registry"
],function(Cache,JsonRest,Memory,parser,on,ready,Button,registry){
console.log('x');
var someData = [
{id:1, name:"One"},
{id:2, name:"Two"},
{id:3, name:"Three"},
{id:4, name:"Four"},
{id:5, name:"Five"}
];
recToQuery = 4;
// recToQuery = 6; // try one that is not in the cache
var memoryStore = new Memory({data: someData});
var restStore = new JsonRest({ target: "/i/dont/exist.json/"});
var myStore = new Cache(restStore, memoryStore);
myStore.query({}); // this will ask for everything and prime the cache
ready(function(){
parser.parse();
var queryBtn = registry.byId("query");
console.log('queryBtn',queryBtn);
on(queryBtn, "click", function() {
console.log('query button clicked',[this,arguments]);
var resultOrPromise = myStore.get(recToQuery);
if (typeof resultOrPromise.then ==='function'){
// it is asking the server
resultOrPromise.then(function(){
console.log('Result from server fetch',arguments);
},function(){
console.log('it queried the server but failed',arguments);
});
}else{
// it is in the cache (from the first query)
console.log('result from cache:',resultOrPromise);
}
});//end connect
}); //end ready
}); //end require