因此,我试图使用Node JS在Heroku中建立一个相当基本的应用程序,而且似乎无法弄清楚如何使上载方法真正起作用,因为每当我上载文件时,heroku都会添加一个/上载到网址末尾。您可以在这里尝试错误,只需上传文件并单击提交:
https://keywordgen.herokuapp.com/
我用于表单的HMTL代码:
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="keywords"/>
<button type="submit">Upload</button>
用于处理所述文件的Node JS代码:
var fs = require('fs'),
path = require('path'),
express = require('express'),
formidable = require('formidable');
var app = express();
var port = 3000;
var output = path.resolve(__dirname, '../keygen_files');
console.log('Output directory: ', output);
// app.use(express.bodyParser());
app.use(express.static(__dirname + '/html'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var newpath = path.resolve(output, files.keywords.name);
console.log('Temp file: ' + files.keywords.path);
fs.rename(files.keywords.path, newpath, function (err) {
if (err) {
res.send('Cannot upload file');
} else {
readFile(newpath, res);
}
});
});
});