【发布时间】:2017-09-28 21:24:24
【问题描述】:
我使用以下代码从文件系统中读取获取文件 代码来自名为 Building a File Uploader with NodeJs 的博文。
当我运行我的项目时,我能够看到 UI 等。
我无法使用以下代码,因为我的项目中没有 uploads 文件夹 (form.uploadDir)
app.post('/upload', function(req, res){
// create an incoming form object
var form = new formidable.IncomingForm();
// specify that we want to allow the user to upload multiple files in a single request
form.multiples = true;
// store all uploads in the /uploads directory - cannot use it
//form.uploadDir = path.join(__dirname, '/uploads');
// every time a file has been uploaded successfully,
// rename it to it's original name
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});
// log any errors that occur
form.on('error', function(err) {
console.log('An error has occurred: \n' + err);
});
// once all the files have been uploaded, send a response to the client
form.on('end', function() {
res.end('success');
});
// parse the incoming request containing the form data
form.parse(req);
});
我的问题是我应该如何使用代码从 UI 获取文件 多于?选择文件时需要从表单中获取文件内容。
应用程序是deployed 到云端,当我使用localhost 时,我使用以下代码(有效)
const readStream = fs.createReadStream("./file.html");
...
const writeStream = sftp.createWriteStream("/index.html");
...
readStream.pipe(writeStream);
它从文件系统中创建一个具有正确路径的文件并用另一个文件覆盖它(比如这里index.html)。
【问题讨论】:
-
文件不是
form.on('file'...回调中的第二个参数 -
@adeneo - 这是我的想法,但 E2E 无法正常工作......(我将应用程序部署到云端,因此很难调试......)有一些简单的方法我可以打印上传到控制台的文件(来自
form.on('file'...)(日志正在工作......),我将能够看到我在表格中选择的文件内容已在云中读取......因此它有点棘手... -
没有云,只是一堆别人的电脑连接在一起。对于记录文件,想到事件处理程序中的
console.log(file)? -
@adeneo - 我使用您的建议,例如:
console.log("the file is-> " + file);,然后我进入控制台OUT the file is-> [object Object],如果我应该写它,我应该使用readStream.pipe(file);?请把它写成答案,我会结束这个问题。谢谢! -
@adeneo - 请添加您的建议作为答案,以便我可以关闭此问题并解决。谢谢
标签: javascript node.js express