Posted at

Node.jsでkintoneにファイルアップロードする

最近よく利用するのでメモします。


upload.js

const DOMAIN = 'sample.cybozu.com';

const AUTHORIZATION = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

const axios = require('axios');
const formdata = require('form-data');
const path = require('path');
const fs = require('fs');

const uploadFile = async (filePath) => {
const url = `https://${DOMAIN}/k/v1/file.json`;

const form = new formdata();
form.append('file', fs.readFileSync(filePath), path.basename(filePath));

const config = {
headers: {
'X-Cybozu-Authorization': AUTHORIZATION,
'Content-Type': form.getHeaders()['content-type']
}
};

try {
let res = await axios.post(url, form, config);
return res.data.fileKey;
} catch (err) {
console.log('err', err);
throw new Error(err);
}
}

async function main() {
let filePath = './image.png';
let fileKey = await uploadFile(filePath);
console.log('fileKey', fileKey);
}

main();