Uploading a file through JS API

cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Active Member II

Uploading a file through JS API

Jump to solution

Hi,
I'm trying to use the https://www.npmjs.com/package/alfresco-js-api  to build an application (Node) aiming to create files in Alfresco.

I have a Community Edition Alfresco installed.

let AlfrescoApi = require('alfresco-js-api');
let alfrescoJsApi = new AlfrescoApi();

let fs = require('fs');

alfrescoJsApi.login('admin', 'admin').then(function (data) {
        console.log('API called successfully login ticket:' + data);
    }, function (error) {
        console.log("Error, cannot connect to Alfresco");
    });

var fileToUpload = fs.createReadStream('./testFile.txt');

alfrescoJsApi.upload.uploadFile(fileToUpload)
        .then(function () {
            console.log('File Uploaded');
        }, function (error) {
            console.log('Error during the upload' + error);
        });

Previous code doesn't work and I don't know why, I can create a folder with  "  alfrescoJsApi.nodes.createFolder();  " but cannot manage to create a file.
In log I'm obtaining following error :

Error during the uploadError: {"error":{"errorKey":"Required parameters are missing","statusCode":400,"briefSummary":"04310053 Required parameters are missing","stackTrace":"Pour des raisons de sécurité, le traçage de la pile n'est plus affiché, mais la propriété est conservée dans les versions précédente.","descriptionURL":"https://api-explorer.alfresco.com"}}

If anyone have any idea of what I'm doing wrong :/

Thanks in advance

1 Solution

Accepted Solutions
Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

Okay so I figured out how to upload a File, once logged and var ticket initialized :

var request = require('request')
var fs = require('fs')

var r = request.post('http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children?alf_ti..., function callback(err, httpResponse, body) {
            if(err || JSON.parse(body).error) {
                return console.log('Upload failed : ' + body)
            }
            console.log('Upload success')
        })

var form = r.form()
form.append("name", "testFile.txt")
form.append("nodeType", "cm:content")
form.append("relativePath", "Sites/test-site/documentLibrary")
form.append("filedata",fs.createReadStream('./testFile.txt'))

I don't use alfresco-js-api anymore

View solution in original post

15 Replies
Highlighted
Advanced II

Re: Uploading a file through JS API

Jump to solution

Well, by looking at the sample code in the project's page, I noticed that all the upload content samples have more parameters besides the content itself.

Samples below got from alfresco-js-api :

this.alfrescoJsApi.upload.uploadFile(fileToUpload, null, null, null, {autoRename: true})
this.alfrescoJsApi.upload.uploadFile(fileToUpload, 'folderX/folderY/folderZ')

var parentFolder = '80a94ac8-3ece-47ad-864e-5d939424c47c';
this.alfrescoJsApi.upload.uploadFile(fileToUpload, 'folderX/folderY/folderZ', parentFolder )

So, for me, it seems the problem is that you are not providing all the required parameters, and because of that, Alfresco is complaining about the message "Required parameters are missing"

Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

Sadly, I tried all these methods, and none of them had a different effect.

EDIT: Looking at the variable 'bodyParam' in the class 'alfrescoApiClient.js' it returned this :

{ name: undefined,
  nodeType: 'cm:content',
  relativePath: 'Sites/test-site/documentLibrary' }

So I added

fileToUpload.name = 'testFile.txt'

And then, in the 'alfrescoApiClient.js' I got

{ name: 'testFile.txt',
  nodeType: 'cm:content',
  relativePath: 'Sites/test-site/documentLibrary' }

But still this error ...

Highlighted
Senior Member II

Re: Uploading a file through JS API

Jump to solution

Looking the  documentation showed me that your file should be uploaded to alfrescos root directory if you use only the filestream parameter. But you should try like Douglas C. R. Paes proposed.

But I think it wouldn't be working at all, because your login call will return a promise immediately. You are not logged in at this moment.

Try to move your upload function into the success conditon (after your console.log for example) of your login function. 

PS: The missing parameter could be the login ticket, that's not defined in the moment of your upload

Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

So, I've put the uploading stuff after the login, added a .name to the Stream, tried every methods proposed before but .... still got this error ...

I really don't understand where it comes from :/

Highlighted
Senior Member II

Re: Uploading a file through JS API

Jump to solution

fileToUpload Is ok, not null? Meaning, can you read it with fileToUpload.read() and log it's contents to the console? 

Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

Well,
console.log(fileToUpload) does display content

but

console.log(fileToUpload.read()) returns null

Highlighted
Senior Member II

Re: Uploading a file through JS API

Jump to solution

...you would have to put ...read() in fileToUpload.on('readable'....

but if console.log(fileToUpload) shows content, your Stream/file is ok.

Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

Yep, I tried to put the upload in events emitted from the readStream but doesn't work either.
And yes .read() worked in 'readable'

Highlighted
Active Member II

Re: Uploading a file through JS API

Jump to solution

I'v also tried directly with

curl -uadmin:admin -X POST localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children -F diledata=@testFile.txt

But as usual ... this error ...

I even tried this :

var http = require("http");

    var options = {
      'host': 'localhost',
      'port': '8080',
      'path': '/alfresco/service/api/login',
      'method': 'POST',
      'content-type': 'application/json',
    };

    var body = {
        'username': 'admin',
        'password': 'admin'
    }

    var req = http.request(options, function(res) {
      console.log('STATUS: ' + res.statusCode);
      console.log('HEADERS: ' + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);


        options.path = 'alfresco/api/-default-/public/alfresco/versions/1/nodes/-root-/children'

        var req2 = http.request(options, function(res) {
          console.log('STATUS: ' + res.statusCode);
          console.log('HEADERS: ' + JSON.stringify(res.headers));
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
          });
        });

        var body = {
            "name":"My folder",  
              "nodeType":"cm:folder",
              "relativePath": 'Sites/test-site/documentLibrary'
        }

        // write data to request body
        req2.write(JSON.stringify(body));
        req2.end();


      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });

    // write data to request body
    req.write(JSON.stringify(body));
    req.end();

Connection returns status 200 ... but uploading returns 400 with no message ...