gpt4 book ai didi

node.js - 使用 Node.js 上传多张图片

转载 作者:搜寻专家 更新时间:2023-10-31 23:53:12 25 4
gpt4 key购买 nike

我正在研究 Node.js 并尝试处理多个图像。我正在使用以下代码上传单个图像,然后将路径以字符串格式保存到数据库中。

 var multiparty = require("multiparty");
var form = new multiparty.Form();

form.parse(req, function(err, fields, files) {
var img = files.image[0];
var fs = require('fs');

fs.readFile(img.path, function(err, data) {
var path = "/path/to/upload/" + img.originalFilename;

fs.writeFile(path, data, function(error) {
if (error) console.log(error);
});
});
})

现在如何处理多个图像。
任何帮助将不胜感激!

最佳答案

var express = require('express'),
app = express(),
formidable = require('formidable'),
util = require('util'),
fs = require('fs-extra'),
bodyparser=require('body-parser'),
qt = require('quickthumb'),
path = require('path');


var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');

var Images = require('./model.js');



app.use(qt.static(__dirname + '/'));
app.use(bodyparser());
app.set('view engine','ejs');


app.post('/upload',function (req, res){

var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
});

form.on('field',function(name,value){

});



form.on('end', function(fields, files) {

for(var x in this.openedFiles)
{
//Images is my model
var img = new Images();

var temp_path = this.openedFiles[x].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[x].name;
//console.log('file '+file_name);
img.size = this.openedFiles[x].size;
img.type = this.openedFiles[x].type;

/* Location where we want to copy the uploaded file */
var new_location = 'uploads/';

console.log(img.nam=new_location+file_name);
img.save(function(err,imgobj) {
if (err)
throw err;
});
//to copy the file into a folder
fs.copy(temp_path, new_location + file_name, function(err) {
if (err) {
console.log(err);
}
});//fscopy
}//for loop

});//form end
res.send('Done!!');

});//post
app.listen(3000);
console.log('started server');

关于node.js - 使用 Node.js 上传多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com