How to upload a document to Alfresco using JavaScript API

I am facing an issue while attempting to upload a file from a node application to my local Alfresco server. I have been able to login, create, and delete folders successfully, but I am encountering difficulties when trying to upload files.

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

alfrescoJsApi.login('admin', 'admin').then(function (data) {

    console.log('Successfully logged in, received ticket:' + data);

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

    fileToUpload.name= "testFile.txt"

    alfrescoJsApi.upload.uploadFile(fileToUpload, 'Sites/test-site/documentLibrary')
        .then(function () {
            console.log('File Uploaded in the root');
        }, function (error) {
            console.log('Error during the upload' + error);
        });

}, function (error) {
    console.log("Error, cannot connect to Alfresco");
});

The above code is throwing the following error:

Error during the uploadError: {"error":{"errorKey":"Required parameters are missing","statusCode":400,"briefSummary":"05010132 Required parameters are missing","stackTrace":"For security reasons, stack trace display has been disabled.","descriptionURL":"https://api-explorer.alfresco.com"}}

I have tried various methods with different parameters as listed here: https://www.npmjs.com/package/alfresco-js-api#upload-file but keep getting the same error. Any help would be greatly appreciated. Thank you =)


EDIT : After struggling with the previous method, I decided to explore using REST requests directly. Here is the code snippet I came up with:

var http = require("http");
var options = {
  'host': 'localhost',
  'port': '8080',
  'path': '/alfresco/service/api/upload?alf_ticket='+ticket,
  'method': 'POST',
  'Content-Type': 'application/json'
};

var fs = require('fs')
var fileToUpload = fs.createReadStream('./testFile.txt');
var body = {
    "filedata": fileToUpload,
    "filename": "testFile.txt",
    "description": "none",
    "siteid": "test-site",
    "containerid": "documentLibrary"
}

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);
    });
});

req.write(JSON.stringify(body));
req.end();

However, now I am receiving an error 500...

STATUS: 500
HEADERS: {"server":"Apache-Coyote/1.1","cache-control":"no-cache","expires":"Thu, 01 Jan 1970 00:00:00 GMT","pragma":"no-cache","content-type":"application/json;charset=UTF-8","transfer-encoding":"chunked","date":"Thu, 01 Jun 2017 14:20:43 GMT","connection":"close"}
BODY: {
    "status" : 
  {
    "code" : 500,
    "name" : "Internal Error",
    "description" : "An error inside the HTTP server which prevented it from fulfilling the request."
  },  

  "message" : "05010287 Unexpected error occurred during upload of new content.",  
  "exception" : "",

  "callstack" : 
  [ 

  ],

  "server" : "Community v5.2.0 (r135134-b14) schema 10 005",
  "time" : "1 juin 2017 16:20:43"
}

I have searched online for solutions but couldn't find any. If anyone has any insights, I would greatly appreciate your help. Thank you.

Answer №1

There seem to be some issues with the line let fs = require('fs');. More details can be found on this link.

Below is an example of a working file upload using an HTML file input element. Minimal modifications were made by adding the necessary code to the default Alfresco Angular component, specifically in the home component where an HTML file upload element was included.

home.component.ts

(Component and login functions included)

home.component.html

(Various components utilizing REST API communication described)
(Additional features integrated into different modules listed) <input type="file" (change)="changeListener($event)"> <button (click)='uploadFileFromUI()'>upload</button>

Answer №2

After some experimentation, I have successfully managed to upload a file:

const fs = require('fs');
const request = require('request');

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

const 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'));

Everything seems to be working smoothly now!

Answer №3

Using the alfresco-js-api library works well, but it seems like you made a mistake in your initial code selection. You should have opted for alfresco-js-api-node instead of alfresco-js-api

Installation for browser versions:

npm install --save alfresco-js-api

Installation for node versions:

npm install --save alfresco-js-api-node

Importing the library for node projects

var AlfrescoApi = require('alfresco-js-api-node');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an image gallery with animated effects: A step-by-step guide

I am looking to develop a creative image gallery with animated effects. I also want to include panels and hyperlinks for each image, similar to the functionality on this website: http://www.microsoft.com/en-lk/default.aspx Can anyone guide me on how to ac ...

Parsing JSON data from Tiled map editor and rendering it onto a canvas

I am currently following a tutorial on how to load JSON map files created by the Tiled Map Editor in my JavaScript/Canvas game. So far, I have implemented my own version without any errors showing up in Firebug or the console. Upon closer inspection with ...

Which is the better choice for me - webpack or create-react-app?

What's the best way to kickstart my react app - webpack or create-react-app? Are there any benefits to using webpack instead of create-react-app? ...

Django Implementation of JavaScript Confirmation Dialogue

Currently working on a Django form that requires a confirm/cancel dialog upon submission. I've considered sending POST data from jQuery, but I'm curious if it's possible to integrate a JavaScript dialog as middleware instead? ...

AngularJS static list with dynamically changing content

Seeking inspiration on creating an AngularJS information monitor with a maximum of 6 rows. The display should show new rows at the top, pushing out the oldest row from the bottom when there are already 6 rows visible. Rows can also disappear unexpectedly. ...

Uncertain about the distinction between reducers and dispatchers when it comes to handling actions

I'm feeling a bit confused regarding reducers and dispatchers. While both receive actions as parameters, it doesn't necessarily mean that the actions I use in my dispatchers are the same as those used in my reducers, correct? For example, if I h ...

How to Utilize Vue and Checkboxes for Filtering a List?

My current challenge involves filtering a list of posts based on userId using checkboxes. The data is being retrieved from: https://jsonplaceholder.typicode.com/posts. I aim to include checkboxes that, when selected, will filter the list by userId. Here is ...

Creating tube-like geometry in intervals using three.js

Is there a way in Tube Geometry(Three.js) to plot and render only a portion of the tube at a time, with the option to continue plotting from that point after a set interval or timer? ...

Use angular-resource to add a new entry to the db.json file

I have a JSON file called db.json with the following structure: { "menu":[ { "id":0, "item":"item1" },{ "id":1, "item":"item2" },{ "id":2, "item":"item3" } ], "feedback":[] } Currently, I am using Angular's $resource to send a Jav ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

"Engaging with the touchscreen inhibits the triggering of click

Within this div, I have implemented touch-action:pan-y;. Surrounding this div is an anchor tag. If you click on the div, the link will successfully redirect. However, if you swipe on the div and then click, the link won't work on the first attempt bu ...

Live Edit API

Currently, I am developing an application that requires near real-time collaborative editing capabilities for documents, similar to the functionality found in Google Documents. Since I am a beginner in this area, I would greatly appreciate any information ...

Transmitting JSON AJAX response to populate location markers on Google Maps

When a button is clicked, an AJAX response is triggered to display JSON data based on a search query. My goal is to take the all_locations variable from the AJAX response and use it to show markers on a Google map. I'm uncertain about how to achieve t ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...

Customize the appearance of the Material UI expansion panel when it is in its expanded

Is there a way to customize the height of an expanded expansion panel summary? Specifically, I am looking to remove the min-height property and set the summary panel's height to 40px instead of the default 64px. I have attempted to make this change in ...

The video is not displaying on the webpage when connected locally, but it appears when the source is a URL

Recently, while practicing some basic tasks on a cloud IDE called Goorm, I encountered an issue with displaying a video on a simple webpage. The EJS file and the video were located in the same folder, but when I set the src attribute of the video tag to "m ...

display a different selection option depending on the previously chosen item

I'm working on displaying additional options in a select box when the user makes a selection from the main select box. I've set display:none for the select boxes, which will only appear when the user chooses an option from the main select box. C ...

Simple method for extracting data from JSON and saving it into an array with jQuery

I have a JSON file containing the resource "A" and literals "B", "C", and "D". My goal is to extract only the items B, C, and D, convert them into strings, and store them in an array. Below is the script I have written for this purpose: <script> // ...

Creating head tags that are less bouncy

After running my code, I noticed that the headlines didn't transition smoothly - they seemed to jump rather than flow seamlessly. To address this issue, I attempted to incorporate fadeIn and fadeOut functions which did improve the smoothness slightly. ...

Getting js.map Files to Function Properly with UMD Modules

I am experiencing an issue with debugging TypeScript files in Chrome and Firefox. Specifically, when trying to debug the MapModuleTest.ts file, the debugger seems to be out of sync with the actual JavaScript code by two lines. This discrepancy makes settin ...