2016-12-07 51 views
0

我剛開始節點返回圖像的URL。我要上傳圖片到服務器,我使用multer的上傳圖片。我使用下面的代碼,我能夠將圖像上傳到服務器,但無法將圖像的URL發送回客戶端的成功響應。任何幫助將是如何使用multer

var request = require('request'); 
var app = require('../app'); 
var util = require('../response_util'); 
var multer = require('multer'); 
var storage = multer.diskStorage({ 
    destination: function (req, file, callback) { 
    callback(null, 'public/upload'); 
    }, 
    filename: function (req, file, callback) { 
    var imageUrl = file.fieldname + '-' + Date.now()+'.jpg'; 
    callback(null, imageUrl); 
    } 
}); 
var upload = multer({ storage : storage }).single('image'); 

app.get('/img/home',function(req,res){ 
    res.send("welcome to image home"); 
}); 

app.post('/img/upload',function(req,res) { 
    upload(req,res,function(err,result) { 
    console.log(err); 
    console.log(result); 
     if(err) { 
      return res.end("Error uploading file."+err); 
     } 
     res.end("File is uploaded url : "+result); 
    }); 
}); 

回答

0
app.post('/img/upload',function(req,res) { 
upload(req,res,function(err,result) { 
console.log(err); 
console.log(result); 
    if(err) { 
     return res.end("Error uploading file."+err); 
    } 
    var path = req.file.path; 
    res.end("File is uploaded url : " + this.path); 
}); 

可以使用req.file.path對象multer需要上傳的文件的路徑。這是爲我工作。