2
這是我的app.js文件:如何將文件上傳到遠程服務器並在nodejs中更改它的路徑?
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。然後該文件不應該保存在我的系統中。
它完美的作品:) – Jagadeesh