In order to upload files into Vault, you need to have some controller that will get and process requests on the server side. Vault uses REST API for processing server-side requests.
In general, the scheme of uploading a file to a server with Vault looks like this:
The example described in this article is based on Node.js.
In the example below the following modules are used:
const Busboy = require('busboy');
const fs = require('fs');
const express = require('express');
const app = express();
In case you want to provide the ability to download files added into Vault, you should specify the path to the directory where files will be stored, e.g.:
app.use('/backend/upload/files/:file', (req, res) => {
var file = __dirname + '/files/'+req.params.file;
res.download(file);
});
Below you can see an example of server-side code that gives an idea of how files upload can be processed. The handler function takes as a parameter the URL for file upload (this URL should be specified in the target configuration option of Vault). It contains the logic of processing an uploaded file:
// upload files
app.post('/backend/upload', (req, res) => {
// check if the request method is "POST"
if (req.method === 'POST') {
// create a busboy instance for stream parsing of a file
const busboy = Busboy({ headers: req.headers });
const response = {};
busboy.on('file', (fieldname, file, { filename }) => {
// define the directory for a file saving
const saveTo = __dirname + "/files/" + filename;
// add the link to this file for response
response.link = `/backend/upload/files/${filename}`;
// save the file
file.pipe(fs.createWriteStream(saveTo));
});
busboy.on('finish', () => {
// return the link to download the file
res.json(response);
})
return req.pipe(busboy);
}
// show error 404 in case the request method is other than POST
res.writeHead(404);
res.end();
});
Form data sent in the request to the server side contains the following fields:
file: (binary)
file_fullname: data.xlsx
file_id: u1552496187456
where:
The server returns a response with one of the two statuses: 200 - in case of success, or error - in case something has gone wrong.
A server response may contain:
{"link":"/vault/backend/upload/files/data.xlsx"}
{"preview":"/vault/backend/upload/files/preview.png"}
Please note that in order to return a link and a preview in the server response, you need to specify the corresponding attributes in the file configuration on the client side.