Con*_*lub 3 upload image file heroku node.js
将图像上传到heroku服务器时遇到一些问题,在localhost上一切正常.但是当我上传图片时,在heroku上,它看起来一切顺利但刷新页面后我收到了错误消息404(未找到)所以它似乎没有上传.
这是我的代码
var express = require('express'),
app = express(),
server = app.listen(process.env.PORT || 5000),
fs = require('fs-extra'),
im = require('imagemagick'),
util = require('util'),
formidable = require('formidable');
app.post('/upload', function (req, res){
var form = new formidable.IncomingForm();
// show respond
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
console.log(fields + ' ' + files);
res.end(util.inspect({fields: fields, files: files}));
});
form.on('end', function(fields, files) {
var that = this;
// temporary storage of image
var temp_path = that.openedFiles[0].path;
// uploaded image name
var file_name = that.openedFiles[0].name;
var dirpath = __dirname + '/app';
var opt = {
thumb : {
width: 150,
height: 150,
dest: '/uploads/thumbnails/'
},
original : {
dest : '/uploads/original/'
}
};
// get extension of image
var extension;
(function(type) {
if (type == 'image/jpeg' || type == 'image/jpg') {
extension = '.jpg';
} else if (type == 'image/png') {
extension = '.png';
}
})(that.openedFiles[0].type);
fs.copy(temp_path, dirpath + opt.original.dest + id + extension, function(err) {
if (err) {
console.error(err);
} else {
// thumbnails
im.crop({
srcPath: dirpath + opt.original.dest + id + extension,
dstPath: dirpath + opt.thumb.dest + id + extension,
width: opt.thumb.width,
height: opt.thumb.height,
quality: 1,
gravity: 'Center'
}, function (err, stdout, stderr){
if (err) {console.log('Thumbnail is not generated')}
else {
}
});
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪里可能有问题?
在云环境中,您不应该将图像上传到实例本身.始终使用像S3这样的中央存储来存储上传的文件.
当您在云环境中进行开发时,应始终牢记您运行代码的当前框只会存在一段时间(分钟,小时).因此,如果实例出现故障,您将丢失所有上传的文件.
例如,当您有2个实例并且您的用户将图像上传到instace x时,可能会出现另一个问题.现在,当第二个用户尝试查看图像但负载均衡器将请求发送到实例y时,找不到该图像,因为该实例上不存在该图像.
为了调试脚本,我会添加一些日志记录.然后在Heroku你可以使用:
heroku logs -t -a appname
Run Code Online (Sandbox Code Playgroud)
查看应用程序的日志.
| 归档时间: |
|
| 查看次数: |
3161 次 |
| 最近记录: |