2017-09-06 42 views
0

使用express創建文件傳輸工具,並且幾乎完成了所有工作。只需要弄清楚如何將請求中的數據寫入文件。從ExpressJS中的發佈請求中寫入文件

我的問題似乎源於不知道文件內容放在請求對象中的位置。

我的代碼來處理髮送請求

let file = watcher.getOneFile(config.thisLocation); 
console.dir(file); 
let contents = fs.readFileSync(file.fullPath, 'utf-8'); 
console.log(contents); 
let form = { 
    attachments: [ 
    contents 
    ] 
} 
rq.post({ 
    url: `http://${homeAddress}:${port}/files/?loc=${config.thisLocation}&file=${file.fileName}`, 
    headers: {'content-type':'application/x-www-form-urlencoded'}, 
    formData: form 
}, (err, res, body) => { 
    // body = JSON.parse(body); 
    console.log(body); 
}); 

,當我得到的服務器上的要求,我不知道該文件的內容居然都是。

代碼處理請求

app.post('/files', (req, res) => { 
    console.log(req.query.loc); 
    // console.dir(req); 
    let incoming = watcher.getOutputPath(req.query.loc, config.locations); 
    console.log(incoming); 
    console.dir(req.body); 
    // console.log(req.body); 
    // let body = JSON.parse(req.body); 
    console.log(req.query); 
    let filename = path.join(incoming, req.query.file); 
    console.log(filename); 
    fs.writeFile(filename, req.body, (err) => { 
    if(err){ 
     console.error(err); 
    } 
    console.log(`Successfully wrote file: ${path.join(incoming, req.query.file)}`); 
    }); 
    res.sendStatus(200); 
}); 

凡請求對象是文件內容是什麼?

+0

你試過'req.file'或'req.files' – turmuka

+0

登錄時他們,他們是未定義。 –

回答

1

不幸的是,您無法以任何直接的方式訪問文件內容。我建議您使用busboy或類似的包來解析表單數據請求。

這裏是你如何可以使用busboy讀取文件內容,並將其寫入文件系統:

const Busboy = require('busboy'); 

app.post('/files', (req, res) => { 
    const busboy = new Busboy({ headers: req.headers }); 

    busboy.on('file', (fieldname, file, filename, encoding, mime) => { 
    const newFilename = `${Date.now()}_${filename}`, 
     newFile = fs.createWriteStream(newFilename); 

    file.pipe(newFile); 

    file.on('end',() => { 
     console.log(`Finished reading ${filename}`); 
    }); 
    }); 

    busboy.on('finish',() => { 
    console.log('Finished parsing form'); 

    res.sendStatus(200); 
    }); 

    req.pipe(busboy); 
}); 
+0

謝謝你。我會試試這個。感謝您更新您的答案。 –

+0

不客氣。如果您對此有任何疑問,請發帖。 – poohitan

+1

剛剛通過PostMan測試,它的工作原理!現在用我的其他代碼來測試! –