[英]How to upload a file and then display its contents in Node.Js Express app?
我一直在努力尋找這個問題的答案:我需要通過Node.Js Express應用程序上傳文本/ html文件,並將其內容保存到變量中以進行進一步處理。
我當然可以制作多部分表格,然后發布內容,但是到目前為止,我只能訪問req.files
,其中包含有關文件的信息,但不包含實際內容。
如何從文件中獲取實際的text / html內容?
我不想將其保存到我的服務器,只需將內容傳遞到我的應用程序並刪除文件,所以我不想使用像formidable
這樣的模塊。
有人可以幫忙嗎?
謝謝!
將multer https://github.com/expressjs/multer與inMemory: true
選項inMemory: true
使用。
作為一個粗略的例子,您將想要做這樣的事情。
app.post('test', function(req, res, next) {
var result = '';
multer({
inMemory: true,
onFileUploadData: function(file, data) {
result += data;
},
onFileUploadComplete: function(file) {
console.log(result); // This is what you want
}
})(req, res, next);
});
該文件默認情況下保存在一個臨時文件夾(可能是/ tmp)中。 您需要打開文件,讀取其內容,然后將其刪除。
您將要使用以下API: http : //nodejs.org/api/fs.html
您可以這樣做:
fs = require('fs');
fs.readFile(req.files.path, function (err, data) {
if (err) throw err;
// data will contain your file contents
console.log(data)
// delete file
fs.unlink(req.files.path, function (err) {
if (err) throw err;
console.log('successfully deleted ' + req.files.path);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.