如何将文件上传到远程服务器并在nodejs中更改它的路径?

时间:2017-06-22 07:00:54

标签: javascript node.js multer-s3

这是我的app.js文件:

var express = require('express')
    , multiparty = require('multiparty')
    , request = require('request')
    , fs = require('fs')
    , util = require('util')
    , http = require('http');

var app = express();
app.use('/static', express.static('static'));

process.on('uncaughtException', function (err) {
    console.log(err);
});

app.get('/', function (req, res) {
    res.redirect('static/index.html');
});

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

    //https://github.com/request/request#streaming

    var form = new multiparty.Form();

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));

    });
    form.on('file', function(name, file) {


    var formData = {
      file: {
        value:  fs.createReadStream(file.path),
        options: {
          filename: file.originalFilename
        }
      }
    };

console.log(formData)
    // Post the file to the upload server
    request.post({url: 'http://192.138.2.73:4000/upload', formData: formData});
    });
});

var server = app.listen(3000, '0.0.0.0' ,function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});

这是upload.js文件:

var express = require('express')
    , multiparty = require('multiparty')
    , cors = require('cors')
    , util = require('util')
    , app = express();

app.use(cors());
process.on('uncaughtException', function (err) {
    console.log(err);
});

app.get('/', cors(), function(req, res, next){
    res.json({msg: 'This is CORS-enabled for all origins!'});
});

app.post('/upload', cors(), function(req, res, next){
    var form = new multiparty.Form();

    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        res.end(util.inspect({fields: fields, files: files}));
    });
    form.on('file', function(name,file) {
        // console.log(file);
        // console.log(name);
    });

});

app.listen(4000, function(){
    console.log('CORS-enabled web server listening on port 4000');
});

我将文件从一个系统上传到另一个系统的远程系统。当我在远程系统中运行upload.js和系统中的app.js时,文件会成功上传到另一个系统,我正在从我的系统上传文件。现在我的问题是我上传的所有文件都被保存在远程系统' / var / tmp'还有我的系统' / var / tmp'。我需要将此路径更改为我自己定义的路径,例如:/ var / www / html / myfolder。然后该文件不应保存在我的系统中。

1 个答案:

答案 0 :(得分:0)

var path_temp = file.path;
var currentFolder = '/var/www/html/..(Your path)';
var filename = path_temp.split('/')[2];
fs.move(path_temp, currentFolder + '/' + filename, function(err) {
 if (err) return console.error(err)
});

将上面的代码粘贴到它将起作用的form.on()函数中。