Last active
December 19, 2015 01:59
-
-
Save intech/5879743 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// we need the fs module for moving the uploaded files | |
var fs = require('fs'), | |
EventEmitter = require('events').EventEmitter; | |
var uploadQueue = new EventEmitter(); | |
uploadQueue.on('upload', function(tmp_path, target_path) { | |
// move the file from the temporary location to the intended location | |
fs.rename(tmp_path, target_path, function(err) { | |
if (err) throw err; | |
// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files | |
fs.unlink(tmp_path, function() { | |
if (err) throw err; | |
uploadQueue.emit('done', tmp_path, target_path); | |
}); | |
}); | |
}); | |
/************************* | |
* как делать неправильно: | |
*************************/ | |
app.post('/file-upload', function(req, res) { | |
// get the temporary location of the file | |
var tmp_path = req.files.thumbnail.path; | |
// set where the file should actually exists - in this case it is in the "images" directory | |
var target_path = './public/images/' + req.files.thumbnail.name; | |
// вешаем событие на завершение обработки для нашего файла | |
uploadQueue.on('done', function(tmp_path, target_path) { | |
// ответ сервера, почему это плохой вариант? потому что всё это время будет открыто соединение, а они лимитированы настройками сервера и шириной канала, а так же пока оно будет открыто будет занята память и кушатся процессорное время. | |
res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes'); | |
}); | |
// в данный момент мы передаём обработку файла в отдельный контекст | |
uploadQueue.emit('upload', tmp_path, target_path); | |
// в идеале сейчас мы должны вернуть ответ, о том, что файл обрабатывается, а когда он обработается уже вывести отдельное оповещение для пользователя. Если в твоей ситуации так делать не нужно, то ты выбрал не тот инструмент, nodejs это не php, он для других целей, для RIA, то есть когда всё подгружается вебсокетами или аяксом и пользователь может видеть в реальном времени всё происходящие не обновляя страницу :) | |
}; | |
/************************* | |
* как делать правильно: | |
*************************/ | |
app.post('/file-upload', function(req, res) { | |
// get the temporary location of the file | |
var tmp_path = req.files.thumbnail.path; | |
// set where the file should actually exists - in this case it is in the "images" directory | |
var target_path = './public/images/' + req.files.thumbnail.name; | |
// вешаем событие на завершение обработки для нашего файла | |
uploadQueue.on('done', function(tmp_path, target_path) { | |
// вернём ответ пользователю через flash-сообщение, которое храниться в сессиях, например после обновления страницы | |
res.flash('info','File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes'); | |
}); | |
// в данный момент мы передаём обработку файла в отдельный контекст | |
uploadQueue.emit('upload', tmp_path, target_path); | |
res.send('Ваш файл загружается, мы сообщим о результатах его обработки в отдельном сообщении.'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment