2015-12-31 2 views
3

Я работаю над Node.js и пытаюсь обрабатывать несколько изображений. Я использую следующий код для загрузки одного изображения, а затем сохранение пути в строковом формате в базу данных.Загрузка нескольких изображений с использованием 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); 
     }); 
    }); 
})  

Теперь, как обрабатывать несколько изображений.
Любая помощь будет оценена!

+0

@ jfriend00: Вы можете получить код сейчас? Я отредактировал это. – Kishor

+0

Я исправил отступ кода для вас. – jfriend00

+0

Могу ли я помочь вам, используя «грозный» модуль вместо «многопартийности»? –

ответ

2
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'); 
+0

Спасибо @ Ketha Kavya. – Kishor

+0

Это помогает мне вставить изображение в базу данных с разными идентификаторами. Можно ли вставить все изображения в формат массива, чтобы я мог вставлять несколько изображений для одного события. – Kishor

+0

@Kishor Это для загрузки нескольких изображений. –

Смежные вопросы