Delete Objects in Bucket with jQuery - autodesk-forge

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}

You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs

Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

Related

Nodejs getting a incomplete response body

I am using http module to send a request to api. So my response body is very large, and I am getting incomplete and when trying to parse to javascript object I am getting an error, that the json is not valid.
Here is my code.
function sendPostRequest(method, url, data, callback) {
if (typeof data === 'undefined') {
data = {};
}
var data = querystring.stringify(data);
var post_options = {
host: API.Host,
port: API.Port,
path: API.Prefix + url,
method: method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + API_USER.token
}
};
var post_req = http.request(post_options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
callback(chunk);
});
});
// post the data
post_req.write(data);
post_req.end();
}
sendPostRequest('GET', 'user/get_accounts', data, function (res) {
res = JSON.parse(res);
mainWindow.webContents.send('user:account', res);
return;
}, true);
Please help to solve this problem! Thanks!
If the data is large and it's provided in chunks(incomplete json) you might have better luck with:
var post_req = http.request(post_options, function (res) {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
callback(rawData);
});
});

Upload Excel file and download from mysql using Node js

I want to upload Excel sheet and after submit that excel sheet need to insert data into mysql database and same sheet which we upload need to download.
I have tried below code:
Node Service-
function getDetails(req, res) {
var sampleFile, fileInfo = {};
var post = req.body;
var ID= post.id;
var name=post.name
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX;
console.log("req.body -- ",req.body);
console.log("Uploaded -- ",sampleFile);
// Get file attributes
var fileId = req.body.fileId;
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var uploadFileName = extractedFilename+'_'+fileId+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
sampleFile.mv(__dirname+'/Myuploads/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
// Update file info
var queryString = "INSERT INTO 'details'('id','name') VALUES ('" + ID + "','" + name + "')";
connection.query(queryString, function(err, result) {
if (!err){
var response = [];
response.push({'result' : 'success'});
if (result.length != 0) {
response.push({'data' : result});
} else {
response.push({'msg' : 'No Result Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
}
});
}
Controller.js
$scope.MyFunction=function(){
var excelForm = new FormData();
excelForm.append('fileInputXLSX', document.getElementById("fileInputXLSX").files[0]);
console.log("---- excelFile : ", document.getElementById("fileInputXLSX").files[0]);
// End : Get File
$http.post(Data.baseNodeService + "getDetails", {
"newProtocolObj": $scope.newProtocolObj
},headconfig).success(function(data, status, headers, config) {
console.log('Details: success');
excelForm.append('fileId', data);
jQuery.ajax({
url: data.baseNodeService + "getDetails",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: excelForm,
success: function(data) {
console.log("---- upload response : ", data);
$scope.goToTfilePage();
}
});
// End : Upload File
}).error(function(map_data, status, headers, config) {
console.log('Details: error');
console.log('status: ', status, '\nmap_data: ', map_data, '\nconfig: ', config);
});
}
Message is coming in console: No file is uploaded.
Please help with the same.It is not upload the file.It is not able to read the response from node service.
I am new in this help in which manner i need to write.
Edit:I am able to upload the file but how to insert into mysql database??

Not able to download OBJ file using GetDerivativeManifest

I am trying to download an OBJ file generated from SVF file, using the Autodesk.Forge .NET API method GetDerivativeManifest (C#). The OBJ file has been created successfully. However, the method does not provide a Stream that I can use to retrieve the file and save it locally.
How can I get the OBJ file?
I don't have a C# sample ready to give you, but I hit the same issue with the Node.js SDK. I worked around by implementing the REST call myself:
download (token, urn, derivativeURN, opts = {}) {
// TODO SDK KO
//this._APIAuth.accessToken = token
//
//return this._derivativesAPI.getDerivativeManifest(
// urn,
// derivativeURN,
// opts)
return new Promise((resolve, reject) => {
const url =
`${DerivativeSvc.SERVICE_BASE_URL}/designdata/` +
`${encodeURIComponent(urn)}/manifest/` +
`${encodeURIComponent(derivativeURN)}`
request({
url: url,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token.access_token
},
encoding: null
}, function(err, response, body) {
try {
if (err) {
return reject(err)
}
if (response && [200, 201, 202].indexOf(
response.statusCode) < 0) {
return reject(response.statusMessage)
}
if (opts.base64) {
resolve(bufferToBase64(body))
} else {
resolve(body)
}
} catch(ex) {
console.log(ex)
reject(ex)
}
})
})
}
Here is how I invoke that method within my endpoint:
/////////////////////////////////////////////////////////
// GET /download
// Download derivative resource
//
/////////////////////////////////////////////////////////
router.get('/download', async (req, res) => {
try {
const filename = req.query.filename || 'download'
const derivativeUrn = req.query.derivativeUrn
// return base64 encoded for thumbnails
const base64 = req.query.base64
const urn = req.query.urn
const forgeSvc = ServiceManager.getService(
'ForgeSvc')
const token = await forgeSvc.get2LeggedToken()
const derivativesSvc = ServiceManager.getService(
'DerivativesSvc')
const response = await derivativesSvc.download(
token, urn, derivativeUrn, {
base64: base64
})
res.set('Content-Type', 'application/octet-stream')
res.set('Content-Disposition',
`attachment filename="${filename}"`)
res.end(response)
} catch (ex) {
res.status(ex.statusCode || 500)
res.json(ex)
}
})
Hope that helps

F5 doesn't work RIGHT on my webapp

i have a strange problem:
we have to make a project in IT, therefore we use AngularJS.
The problem is, when I use F5 for refresh, the page loads, but it is not able to show the right content again. There's just background and my title, everything in my UI-VIEW isn't there.
We have Login-Page with redirecting:
app.run(function($rootScope, $location, sessionFactory) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
let loggedIn = sessionFactory.isAuthenticated();
if (toState.authenticate && !loggedIn) {
event.preventDefault();
$state.go('login');
}
});
});
without this redirecting block, F5 works.
Otherwise I have to go to Login-Page and login again to get it work again.
I'm sorry guys, I'm new at programming. So if there's any code you need, just let me know. Hope someone can help.
UPDATE: this is our authentification_service.js
a group member wrote it. Does it help?
var app = angular.module('TheApp');
/**
* This service manages sessions: Retrieving token from server and storing token data.
*/
app.factory('sessionFactory', ['$http', 'jwtDecoder', function($http, jwtDecoder) {
var sessionFactory = {
sessionData: null
};
sessionFactory.login = function(username, password) {
//todo: encrypt password....
var user = { username : username, password : password};
// returns a POST request, success or error of that request
// must be handled by the caller of the login function
return $http({
method: 'POST',
url: 'rest/auth/login',
data: user
});
};
sessionFactory.logout = function() {
return $http({
method: 'POST',
url: 'rest/auth/logout',
data: this.sessionData
});
}
sessionFactory.deleteSessionData = function() {
this.sessionData = null;
}
sessionFactory.setSessionData = function(sessionData) {
this.sessionData = {
token: sessionData.token,
userData: jwtDecoder.getUserData(sessionData.token) // holds user id, todo: permissions
};
console.log(this.sessionData.userData);
};
sessionFactory.getToken = function() {
return this.sessionData.token;
};
sessionFactory.getUserId = function() {
return this.sessionData.userData.userId;
}
sessionFactory.isAuthenticated = function() {
return this.sessionData != null;
};
return sessionFactory;
}]);
/**
* This service injects authentification token in HTTP requests.
*/
app.factory('tokenInjector', ['$injector', function($injector) {
var tokenInjector = {
request: function(config) {
// cannot use sessionFactory directly, because else Angular will spot a circular dependency -> error
var sessionFactory = $injector.get('sessionFactory');
// if the user is logged in, add an Authorization header (with token) to each http request
if(sessionFactory.isAuthenticated()) {
config.headers.Authorization = 'Bearer ' + sessionFactory.getToken();
//config.url = config.url + "?token=" + sessionFactory.getToken(); // add token to request url
}
return config;
}
};
return tokenInjector;
}]);
/**
* Decodes JWTs received from the server with a JWT deconding lib
* and returns a useable result.
*/
app.factory('jwtDecoder', function() {
var jwtDecoder = {};
// extracts all needed frontend user data from token
jwtDecoder.getUserData = function(token) {
var payload = jwt_decode(token);
var userData = {
userId: payload.userId //,
//groupId: ?,
//permissions: payload.permissions, // is array of perm
};
return userData;
}
return jwtDecoder;
})

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};