2016-10-03 50 views
0

我正在使用fs在我的web應用程序中上傳文件,但控制檯顯示文件已保存到我輸入的所需位置,但該文件沒有顯示在那裏。如何使用Mean app中的文件系統I/O上傳文件?

的代碼是在這裏: -

var fs = require('fs-extra'); 
var path = require('path'); 

module.exports.updatePhoto = function(req,res) { 
var file = req.files.file; 
var userId = req.body.userId; 

console.log("User "+ userId +" is submitting ", file); 
var uploadDate = new Date(); 

var tempPath = file.path; 
var targetPath = path.join(__dirname, "../../uploads/" + userId + uploadDate +file.name); 
var savePath = "/uploads/" + userId + uploadDate + file.name; 

fs.rename(tempPath, targetPath,function(err){ 
if(err) { 
    console.log(err); 
} 
else { 
    User.findById(userId, function(err, userData){ 
     var user = userData; 
     user.image = savePath; 
     user.save(function(err){ 
      if(err) { 
       console.log("failed") 
       res.json({status: 500}) 
      } 
      else { 
       console.log("saved"); 
       res.json({status: 200}) 
      } 
     }) 
    }) 
} 
}) 
}; 
+0

你應該張貼你已經做了代碼,以便我們可以對其進行審覈。我之前已經完成了這個工作。我的代碼已被添加到 – Enkode

+0

。請檢查它。 –

回答

0

是否使用連接多黨擺脫Express中的文件? https://github.com/expressjs/connect-multiparty

我最終將文件加載到AWS。所以我能提供的最好的代碼就是做這件事。這對我的使用基本上是免費的,我使用碼頭重建我的網站,這使得它更加靈活。

我File.Js:

'use strict'; 

module.exports = function (app) { 

    /** 
    * Module dependencies. 
    */ 
    var auth = require('../config/auth'), 
    api = {}, 
    multiparty = require('connect-multiparty'), 
    multipartyMiddleware = multiparty(), 
    path = require('path'), 
    uuid = require('node-uuid'), 
    fs = require('fs'), 
    S3FS = require('s3fs'); 

    var s3fsImpl = new S3FS('FOLDER_NAME_ENTER_HERE', { 
    accessKeyId: process.env.AWS_ACCESS_KEY_ID, 
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY 
    }); 

    /** 
    * Saves the logo file to the server 
    */ 
    api.uploadImage = function(req, res) { 
    // We are able to access req.files.file thanks to the multiparty middleware 
    var folder = req.params.folder; 
    var file = req.files.file; 

    var filename = uuid.v4() + path.extname(file.name); 
    var stream = fs.createReadStream(file.path); 
    s3fsImpl.writeFile(folder + '/' + filename, stream).then(function() { 
     fs.unlink(file.path, function (err) { 
     if (err) { 
      console.error(err); 
     } 
     }); 
     return res.status(200).json({'fileName': filename, 'url': 'https://s3-us-west-2.amazonaws.com/AWS_FOLDER_ENTER_HERE' + folder + '/' + filename}); 
    }); 
    }; 

    /** 
    * Routes 
    */ 
    app.route('/api/files/:folder/uploadImage') 
    .post(auth.jwtCheck, multipartyMiddleware, api.uploadImage); 

}; 
相關問題