我不知道如何将从可怕的文件正确保存到服务器正在运行的文件系统。
我能够console.log文件,但是我不知道该怎么处理那里提供的信息。
app.post("/sendImages", (req, res) => {
const files = req.files;
Object.keys(files).forEach((key) => {
console.log(files[key]);
fs.writeFile('images/' + files[key].name, files[key], 'binary', (error) => {
if (error) console.log(error);
else console.log('image created');
});
})
});
此请求处理程序在此处创建具有正确名称的文件,但是当我尝试在VS Code中打开它们时,我唯一看到的就是[object Object]。
控制台记录文件的示例:
File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 3835864,
path:
'C:\\Users\\MY_USER_DIR\\AppData\\Local\\Temp\\upload_b099c61751b3b25772344e20df06a4d9',
name: '20190602_134136.jpg',
type: 'image/jpeg',
hash: null,
lastModifiedDate: 2019-06-30T15:03:22.060Z,
_writeStream:
WriteStream {
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: true,
needDrain: true,
ending: true,
ended: true,
finished: true,
destroyed: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: false,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
path:
'C:\\Users\\MY_USER_DIR\\AppData\\Local\\Temp\\upload_b099c61751b3b25772344e20df06a4d9',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 3835864,
closed: false } }
我希望你们中的某人可以告诉我我在这里做错了什么,我一般来说对Node都是新手,但到处仍然有一些问题:)
答案 0 :(得分:0)
您应该将文件从tmp文件夹复制到images文件夹,例如(Node.js >= 8.5.0
):
const fs = require('fs');
const util = require('util');
const path = require('path');
const copyFile = util.promisify(fs.copyFile);
app.post('/sendImages', async (req, res) => {
const files = req.files;
const results = Object.keys(files).map((key) => {
const file = files[key];
const dest = path.join('images/', file.name);
return copyFile(file.path, dest);
});
await Promise.all(results);
// ...
});
如果您不想将文件保存到tmp文件夹,则应检查api文档以更改uploadDir。像express-formidable:
app.use(formidableMiddleware({
encoding: 'utf-8',
uploadDir: 'images/',
multiples: true
});