64 lines
2.0 KiB
JavaScript
64 lines
2.0 KiB
JavaScript
const os = require('os');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
exports.download_file_id = async function (axios, file_id, filename_override) {
|
|
console.log('Downloading file...');
|
|
const url = '/event/file/'+file_id+'/download';
|
|
|
|
const data = await axios({
|
|
method: "get",
|
|
url: url,
|
|
responseType: "stream"
|
|
})
|
|
.then(function (response) {
|
|
//console.log(response);
|
|
//console.log(response.data);
|
|
|
|
let filename = 'default.txt';
|
|
|
|
if (typeof filename_override === 'undefined' || filename_override == null) {
|
|
let headerLine = response.data.headers['content-disposition'];
|
|
|
|
console.log(headerLine);
|
|
console.log(headerLine.indexOf('="'));
|
|
console.log(headerLine.indexOf('='));
|
|
if (headerLine.indexOf('="') != -1) {
|
|
let startFileNameIndex = headerLine.indexOf('="') + 2;
|
|
let endFileNameIndex = headerLine.lastIndexOf('"');
|
|
filename = headerLine.substring(startFileNameIndex, endFileNameIndex);
|
|
} else if (headerLine.indexOf('=') != -1) {
|
|
let startFileNameIndex = headerLine.indexOf('=') + 1;
|
|
let endFileNameIndex = headerLine.length;
|
|
filename = headerLine.substring(startFileNameIndex, endFileNameIndex);
|
|
} else {
|
|
filename = 'filename_not_found_in_header.txt';
|
|
}
|
|
} else {
|
|
filename = filename_override;
|
|
}
|
|
|
|
let directory = 'file_cache/';
|
|
|
|
directory_and_filename = path.join(directory, filename);
|
|
|
|
//console.log(directory_and_filename);
|
|
|
|
if (fs.existsSync(directory_and_filename)) {
|
|
console.log('File already exists: '+directory_and_filename);
|
|
} else {
|
|
console.log('Starting file download: '+directory_and_filename);
|
|
response.data.pipe(fs.createWriteStream(directory_and_filename));
|
|
}
|
|
//data = response.data;
|
|
return true;
|
|
//return response.data;
|
|
})
|
|
.catch(function (error) {
|
|
console.log(error);
|
|
return error;
|
|
});
|
|
|
|
return data;
|
|
}
|