nfp_sites/api/media/upload.mjs

78 lines
1.8 KiB
JavaScript
Raw Normal View History

2019-02-20 16:10:37 +00:00
import http from 'http'
import path from 'path'
import fs from 'fs'
2019-09-14 19:03:38 +00:00
import config from '../config.mjs'
2019-02-20 16:10:37 +00:00
let stub
export function uploadFile(token, file) {
// For testing
if (stub) return stub(token, file)
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) return reject(err)
const crlf = '\r\n'
const filename = path.basename(file)
const boundary = `--${Math.random().toString(16)}`
const headers = [
`Content-Disposition: form-data; name="file"; filename="${filename}"` + crlf,
]
const multipartBody = Buffer.concat([
new Buffer(
`${crlf}--${boundary}${crlf}` +
headers.join('') + crlf
),
data,
new Buffer(
`${crlf}--${boundary}--`
),
])
const options = {
2019-09-13 13:33:10 +00:00
port: config.get('upload:port'),
hostname: config.get('upload:host'),
2019-02-20 16:10:37 +00:00
method: 'POST',
path: '/media?token=' + token,
headers: {
'Content-Type': 'multipart/form-data; boundary=' + boundary,
'Content-Length': multipartBody.length,
},
}
const req = http.request(options)
req.write(multipartBody)
req.end()
req.on('error', reject)
req.on('response', res => {
res.setEncoding('utf8')
let output = ''
res.on('data', function (chunk) {
output += chunk.toString()
})
res.on('end', function () {
try {
output = JSON.parse(output)
} catch (e) {
2019-09-13 13:33:10 +00:00
return reject(e)
}
if (output.status) {
return reject(new Error(`Unable to upload! [${output.status}]: ${output.message}`))
2019-02-20 16:10:37 +00:00
}
resolve(output)
})
})
})
})
}
export function overrideStub(newStub) {
stub = newStub
}