我正在尝试将图像上传到Firebase云功能。我认为我已经阅读了有关此内容的全部文章,但找不到解决方法。
我使用过“ formidable.IncomingForm()”,“ multer”和“ busboy”,但是没有人在工作。
我了解到我必须使用busboy。我想与此库共享我的最后代码。
app.post('/',function(req,res) {
var busboy = new Busboy({headers: req.headers});
var files = 0, finished = false;
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('File [' + fieldname + ']: filename: ' + filename);
console.log("Uploading: " + filename);
++files;
// const temp = os.tmpdir();
// var path = temp.writeFileSync(file);
let path=os.tmpdir()+"/"+filename
let p=fs.writeFileSync(path,file)
console.log(path)
var fstream = fs.createWriteStream(path);
fstream.on('finish', function () {
if (--files === 0) {
// Upload a local file to a new file to be created in your bucket.
bucket.upload(path,function (err, file) {
if (!err) {
console.log("Uploaded: " + path);
res.json({
uploaded: true,
created_at: new Date().getTime(),
filename: filename,
mimeType: mimetype
});
}else{
console.error("err: " + err);
var error = new ErrorResponse(400);
error.errors+=err;
res.json(error);
}
});
}
});
file.pipe(fstream);
})
req.pipe(busboy);
})
此代码在我的本地服务器中成功上传文件,但在Firebase Cloud功能中没有成功上传文件。
问题在于函数“ busboy.on('file'...”永远不会执行
答案 0 :(得分:2)
由于我是busboy
的菜鸟。我会坚持使用最受欢迎的图书馆multer
。
使用multer's
内存存储,将图像上传为缓冲区。然后使用该缓冲区将图像上传到存储桶。
尝试以下代码段:
var multer = require('multer')
// using the in-memory storage
var upload = multer()
// use the same paramter you are using for uploading from postman
app.post('/', upload.single('file'), function(req, res) {
const fileBuff = req.file.buffer
const fileName = req.file.filename
const mimeType = req.file.mimetype
const file = myBucket.file(fileName);
file.save(fileBuff)
.then(success => {
res.json({
uploaded: true,
created_at: new Date().getTime(),
filename: fileName,
mimeType: mimeType
});
})
.catch(err => {
console.error("err: " + err);
var error = new ErrorResponse(400);
error.errors += err;
res.json(error);
})
})
答案 1 :(得分:1)
Harroon Khan的解决方案不适用于当前测试的原因是因为您实际上并未使用邮递员将文件发送到端点,而只是发送了文件名。
>这是有问题的,因为端点只能在本地开发环境中工作。
与邮递员发送实际文件时,应尝试使用他的解决方案。以下是一些截图,向您展示了如何切换它:
使用邮递员上传文件
答案 2 :(得分:0)
此代码对我有用!我不知道为什么,但是我必须写一个文件,然后读取它,最后将我读取的数据上传到存储设备
ex.post('/upload', function(req, res) {
const busboy = new Busboy({
headers: req.headers
});
const tmpdir = os.tmpdir();
// This object will accumulate all the fields, keyed by their name
const fields = {};
// This object will accumulate all the uploaded files, keyed by their name.
const uploads = {};
// This code will process each non-file field in the form.
busboy.on('field', (fieldname, val) => {
// TODO(developer): Process submitted field values here
console.log(`Processed field ${fieldname}: ${val}.`);
fields[fieldname] = val;
});
const fileWrites = [];
// This code will process each file uploaded.
busboy.on('file', (fieldname, file, filename) => {
// Note: os.tmpdir() points to an in-memory file system on GCF
// Thus, any files in it must fit in the instance's memory.
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
console.log("PATH: "+filepath)
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
// File was processed by Busboy; wait for it to be written to disk.
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});
// Triggered once all uploaded files are processed by Busboy.
// We still need to wait for the disk writes (saves) to complete.
busboy.on('finish', () => {
Promise.all(fileWrites).then(() => {
// TODO(developer): Process saved files here
for (const name in uploads) {
const file = uploads[name];
let data = fs.readFileSync(uploads[name]);
const filetoGCF = bucket.file("file-name");
filetoGCF.save(data)
.then(success => {
res.json({
uploaded: true,
created_at: new Date().getTime(),
filename: 'file-name',
});
})
fs.unlinkSync(file);
}
}).catch((err)=>{
res.json({
uploaded: false,
error: err,
});
});
});
busboy.end(req.rawBody);
})
感谢Haroon Khan的帮助!