我使用下面的代码从文件系统中读取get文件 该代码来自名为 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);
});
My question is how should I get the file from the UI with the code above? I need to get the file content from the form when I choose my file.
应用程序被部署
到云端,当我使用localhost
时,我使用以下代码(有效)
const readStream = fs.createReadStream("./file.html");
...
const writeStream = sftp.createWriteStream("/index.html");
...
readStream.pipe(writeStream);
它从具有正确路径的文件系统创建一个文件并用另一个文件覆盖它(如这里的 index.html
)。
最佳答案
正如@aedneo 所说,当用户选择文件时,文件会在上传文件夹中创建,我只需要重命名它并为写入流方法提供正确的路径即可!
关于javascript - 从表单上传文件中读取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46478552/