Multer没有将文件保存为文件
问题描述:
我已经将multer设置为路由上的中间件。当该路线被击中时,multer不会下载该文件。这是CONSOLE.LOG报道:Multer没有将文件保存为文件
{ firstname: 'foo',
lastname: 'foo',
username: 'foo10',
password: 'test1234',
file: '/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAAB.....
}
我有multer以下设置:
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, '../images/profile');
},
filename: function(req, file, cb) {
cb(null, req.body.username + '.jpeg');
}
});
var upload = multer({storage: storage});
router.post('/auth/signup', upload.single('file'), function(req,res) {
console.log(req.body);
});
所以,问题在于不是将文件保存为一个文件,它只是将其视为另一个关键在形式中的值对。
为了进一步澄清,我获得从科尔多瓦API此图像: http://ionicframework.com/docs/v2/native/camera/
import { Camera } from 'ionic-native';
Camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
let base64Image = 'data:image/jpeg;base64,' + imageData;
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
formData.append("file", base64Image);
xhr.onreadystatechange =() => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.open('POST', 'http://localhost:8080/auth/signup', true);
xhr.send(formData);
}, (err) => {
// Handle error
});
答
文件数据正在上载为Base64串,这表明它没有被上传作为一个适当的File
形式的数据字段。这就是为什么multer
将其视为常规字段,并且不会尝试将其保存到文件。
在this answer中,提供了一些客户端代码来处理数据URI字符串(如base64Image
)以正确的格式上传到服务器。
我不明白吗?您正在尝试保存文件并且无法正常工作?发生什么事? –
澄清添加 – runtimeZero
这看起来像一个Base64编码的JPEG。你确定你的客户端代码正确地上传表单数据吗? – robertklep