create file object using file path instead of input file form - autodesk-forge

most if not all Forge samples used input file form to get input file like below:
$("#inputFile").change(function () {
_fileInputForm = this;
if (_fileInputForm.files.length === 0) return;
var file = _fileInputForm.files[0];
}
what if i want to achieve the same result without UI at all? something like below:
const data = {
ModelId: "dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLjNSTzhMWmtUVGVHM3p1M1FoNjRGM3c_dmVyc2lvbj0x",
ElementId: [{ UniqueId: "ca5762b5-0f46-4a2f-8599-1d1a5dd19a81-00024b8c" }],
};
var file = new File([data], "whatever.json", { type: "application/json" });
data is manually copied from whatever.json, how to do it via code? thanks

Related

How can I pass a base64 pdf to the server-side in Google Apps Script?

Overall Goal
Generate a pdf of the currently displayed html page;
Pass it to the server-side;
Save into a specific Google Drive
Item 2 is the one I'm having trouble with!
I'm using this to try to get the converted file passed to the server-side:
Client Side
function saveToGDrive(){
var element = document.getElementById('pgBody');
var opt = {
margin: 1,
filename: 'myfile.pdf',
image: {
type: 'jpeg',
quality: 0.98
},
html2canvas: {
scale: 5
},
jsPDF: {
unit: 'in',
format: 'A4',
orientation: 'landscape'
}
};
const pg = html2pdf().set(opt).from(element).outputPdf().then(function(p) {
console.log('PDF file: ' + typeof btoa(p))
return btoa(p);
});
google.script.run.savePdf(pg)
}
Item 2 gives me the error: Failed due to illegal value in property: state and I'm taking the variable pg is too large to be passed as a parameter like this.
Appreciate any help!
When your showing script is modified, how about the following modification?
From:
const pg = html2pdf().set(opt).from(element).outputPdf().then(function(p) {
console.log('PDF file: ' + typeof btoa(p))
return btoa(p);
});
google.script.run.savePdf(pg)
To:
html2pdf().set(opt).from(element).outputPdf().then(function(p) {
google.script.run.savePdf(btoa(p));
});
When this script is run, the base64 data of btoa(p) is sent to the Google Apps Script side.
When savePdf is the following script, the base64 data is converted to a Blob and saved as a PDF file on Google Drive.
const savePdf = e => DriveApp.createFile(Utilities.newBlob(Utilities.base64Decode(e), MimeType.PDF).setName("samplename.pdf"));

I want to change the .name of an uploaded filein Vue.js

So I have this file input where the user selects an image. But once I have this image, I want to change ONLY the name, so for example, user uploads "wallpaper_hd_dragonball_z.jpg" and I want it to be named "wallpaper.jpg". This is the input:
<input type="file" #change="uploadImage($event,userDetails.email)">
And this is the function it calls to store the image in the database:
uploadImage(e, email){
this.selectedFile = e.target.files[0];
console.log(this.selectedFile.name);
var storageRef = firebaseApp.storage().ref(`profilePics/${email}/${this.selectedFile.name}`);
const task = storageRef.put(this.selectedFile);
task.on('state_changed',snapshot=>{
let percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
this.uploadValue = percentage;
}, error=>{console.log(error.message)},
()=>{this.uploadValue=100;
task.snapshot.ref.getDownloadURL().then((url)=>{
this.picture = url;
console.log(this.picture);
})
})
}
Basically what I'm trying is:
this.selectedFile.name = "profPic.jpg";
console.log(this.selectedFile.name);
But it doesn't work. I've looked around google and I can't find how to do it.
You don't have to change the name of the file you have in memory, because the name property of a File object is read-only.
Instead, just rename the file you will save in Firebase Storage.
function getFileExtension(fileName) {
return filename.split('.').pop();
}
//...
const fileExtension = getFileExtension(this.selectedFile.name);
var storageRef = firebaseApp.storage().ref(`profilePics/${email}/wallpaper.${fileExtension}`);
storageRef.put(this.selectedFile);
// ...
Or create a new file object, with another name.
const myNewFile = new File([this.selectedFile], 'wallpaper.png', {type: myFile.type});
firebaseApp.storage().ref(`profilePics/${email}/${myNewFile.name}`);
storageRef.put(myNewFile);
// ...

json object to file in D3 V4,V5

I'm able to read a .csv file with d3.csv, stratify it and try to save the object to a file to generate a .json file for D3 graphs. Basically I'm doing a simple converter csv to json.
I'm using D3 V5 and FileSaver.js libraries only. Code runs fine until I arrive to JSON.stringify call that crashes. How can I safely save the root object generated in a .json file ?
.csv format file is also simple, first row is header describing row format: id, parentId, size
Code I'm using is simple:
(function () {
"use strict";
var filecsv = "data/Who.csv",
filejson = "data/Who.json";
const partition = data => {
const root = d3.hierarchy(data)
.sum(d => d.data.size)
.sort((a, b) => b.value - a.value);
return d3.partition()
.size([2 * Math.PI, root.height + 1])
(root);
};
d3.csv(filecsv).then(function(vCsvData) {
var data = d3.stratify()(vCsvData);
var root = partition(data);
var blob = new Blob([JSON.stringify(data)], {type: "text/plain;charset=utf-8"}); // crash here
saveAs(blob, filejson);
})
.catch(function(error){
console.log("Something wrong reading data from csv file...");
});
}());

Button for markupCore extension not showing in dockingpanel

I have followed Philippe Leefsma's tutorial on how to implement the markup tool, but without any luck. Link here: http://adndevblog.typepad.com/cloud_and_mobile/2016/02/playing-with-the-new-view-data-markup-api.html
and here: https://developer.api.autodesk.com/viewingservice/v1/viewers/docs/tutorial-feature_markup.html
I get errors that I need to include requireJS, but I don't want to use it. So instead I used this script in my html file:
<script src="https://autodeskviewer.com/viewers/2.2/extensions/MarkupsCore.js">
I don't know if this is the right way to go? I get no errors in the console, but the markup button doesn't show up in the dockingpanel.
This is my code for loading the extension in the viewer:
viewerApp = null;
function initializeViewer(containerId, urn, params) {
function getToken(url) {
return new Promise(function (resolve, reject) {
$.get(url, function (response) {
resolve(response.access_token);
});
});
}
var initOptions = {
documentId: 'urn:' + urn,
env: 'AutodeskProduction',
getAccessToken: function (onGetAccessToken) {
getToken(params.gettokenurl).then(function (val) {
var accessToken = val;
var expireTimeSeconds = 60 * 30;
onGetAccessToken(accessToken, expireTimeSeconds);
});
}
}
function onDocumentLoaded(doc) {
var rootItem = doc.getRootItem();
// Grab all 3D items
var geometryItems3d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '3d' }, true);
// Grab all 2D items
var geometryItems2d =
Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, { 'type': 'geometry', 'role': '2d' }, true);
// Pick the first 3D item otherwise first 2D item
var selectedItem = (geometryItems3d.length ?
geometryItems3d[0] :
geometryItems2d[0]);
var domContainer = document.getElementById('viewerContainer');
var config = { extensions: ["Autodesk.Viewing.MarkupsCore"] };
// GUI Version: viewer with controls
var viewer = new Autodesk.Viewing.Private.GuiViewer3D(domContainer, config);
viewer.loadExtension("Autodesk.Viewing.MarkupsCore");
viewer.initialize();
viewer.loadModel(doc.getViewablePath(selectedItem));
var extension = viewer.getExtension("Autodesk.Viewing.MarkupsCore");
viewerApp = viewer;
}
function onEnvInitialized() {
Autodesk.Viewing.Document.load(
initOptions.documentId,
function (doc) {
onDocumentLoaded(doc);
},
function (errCode) {
onLoadError(errCode);
})
}
function onLoadError(errCode) {
console.log('Error loading document: ' + errCode);
}
Autodesk.Viewing.Initializer(
initOptions,
function () {
onEnvInitialized()
})
}
Any help is highly appreciated!
Unfortunately there has been a few changes to the API since I wrote that blog post. The MarkupCore.js is now included in the viewer3D.js source, so you don't need to reference any extra file or use requireJS if you use the latest version of the viewer API.
Keep in mind that this is an API-only feature, so even after loading the markup extension, you won't get any UI out of the box. You have to implemented it yourself, for example create a dialog with buttons that may eventually create markups by calling the API.
Some of the code from my blog post may still be valid and give you an idea about what you need to do.
Hope that helps.

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible