-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (51 loc) · 1.52 KB
/
server.js
File metadata and controls
58 lines (51 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const express = require('express');
const app = express();
const fileUpload = require('express-fileupload');
const ipfsAPI = require('ipfs-api');
const ipfs = ipfsAPI({host: '0.0.0.0', port: '5001', protocol: 'http'});
let LIMIT_IN_BYTES = 1024 * 100;
app.use(fileUpload({
saveFileNames: true,
preserveExtension: true,
}));
app.post('/set', function(req, res) {
// Check the file is under 100k
if (!req.files) {
return res.send({
success: false,
error: 'No files were selected to upload in field \'file\'',
});
}
if (req.files.file.data.length > LIMIT_IN_BYTES) {
return res.json({
success: false,
error: `The field 'file' cannot be more than ${LIMIT_IN_BYTES / 1024}kb in size`,
});
}
ipfs.files.add([{
path: req.files.file.name,
content: req.files.file.data,
}], (err, resp) => {
if (err) {
return res.send({success: false, error: 'Unable to save file', err});
}
// eslint-disable-next-line no-undef
pinHash(resp[0].hash);
res.send({success: true, file: {
path: resp[0].path,
hash: resp[0].hash,
size: resp[0].size,
}});
});
});
app.get('/get/:hash', function(req, res) {
var hash = req.params.hash;
ipfs.files.get(hash, function(err, stream) {
stream.on('data', (file) => {
file.content.pipe(res);
});
});
});
const PORT = 9000;
const HOST = '0.0.0.0';
app.listen(PORT, HOST);