node.jsのアップロードファイルをサーバにアップロード
3342 ワード
//Buffer split
let buffer = new Buffer('abc\r
ddasdfafd\r
dfaerewtwert');
function bufferSplit(buffer, delimiter){
let res = [];
let n = 0;
while((n = buffer.indexOf(delimiter)) !== -1){
res.push(buffer.slice(0, n));
buffer = buffer.slice(n + delimiter.length);
}
res.push(buffer);
return res;
}
console.log(bufferSplit(buffer, '\r
').map(e => e.toString()));
// node.js post
const http = require('http');
const util = require('buffer_util.js');
const fs = require('fs');
http.createServer((req, res) => {
let boundary='--'+req.headers['content-type'].split('; ')[1].split('=')[1];
let arr = [];
req.on('data', Buffer => {
arr.push(Buffer);
});
req.on('end', () => {
let buffer = Buffer.concat(arr);
let res = util.bufferSplit(buffer, boundary);
// console.log(res);
res.pop();
res.shift();
res.forEach(buffer => {
buffer = buffer.slice(2, buffer.length - 2);
let n = buffer.indexOf('\r
\r
');
let info=buffer.slice(0, n).toString();
let data=buffer.slice(n+4);
// console.log(info);
/*
Content-Disposition: form-data; name="username"
Content-Disposition: form-data; name="password"
Content-Disposition: form-data; name="f1"; filename="prototype.png"
Content-Type: image/png
*/
if(info.indexOf('\r
') !== -1){
//
let res2 = info.split('\r
')[0].split(';');
let name = res2[1].split('=')[1];
let filename = res2[2].split('=')[1];
name = name.substring(1, name.length-1);
filename = filename.substring(1, filename.length-1);
// console.log(name); //"f1"
fs.writeFile(`upload/${filename}`, data, err => {
if(err){
console.log(err);
}else{
console.log(' ');
}
})
}else{
//
let name = info.split('; ')[1].split('=')[1];
name = name.substring(1, name.length - 1);
console.log(name)
}
})
});
}).listen(8080);
// multiparty
const http = require('http');
const multiparty = require('multiparty');
http.createServer((req, res)=>{
let form = new multiparty.Form({
uploadDir: './upload'
});
form.parse(req);
form.on('field', (name, value) => {
console.log(' :', name, value);
});
form.on('file', (name, file) => {
console.log(' :', name, file);
});
form.on('close', () => {
console.log(' ');
});
}).listen(8080);
// CORS
const http=require('http');
let allowOrigin={
'http://localhost': true,
'http://aaa.com': true,
'https://aaa.com': true,
}
http.createServer((req, res)=>{
let {origin}=req.headers;
if(allowOrigin[origin]){
res.setHeader('access-control-allow-origin', '*');
}
res.write('{"a": 12, "b": "Blue"}');
res.end();
}).listen(8080);