Remove temporary files when uploading images

closes #502
part of #705
- copy the files but then remove the temporary ones
- moving instead of copying was problematic due to moving across devices
- still need to convert code to using promises
This commit is contained in:
jamesbloomer 2013-09-18 09:59:42 +01:00
parent 65e00f8418
commit 36f218abaf
2 changed files with 30 additions and 12 deletions

View File

@ -84,19 +84,24 @@ adminControllers = {
// adds directories recursively
fs.mkdirs(dir, function (err) {
if (err) {
errors.logError(err);
} else {
fs.copy(tmp_path, target_path, function (err) {
if (err) {
errors.logError(err);
} else {
// TODO: should delete temp file at tmp_path. Or just move the file instead of copy.
// the src for the image must be in URI format, not a file system path, which in Windows uses \
var src = path.join('/', target_path).replace(new RegExp('\\' + path.sep, 'g'), '/');
res.send(src);
}
});
return errors.logError(err);
}
fs.copy(tmp_path, target_path, function (err) {
if (err) {
return errors.logError(err);
}
fs.unlink(tmp_path, function (e) {
if (err) {
return errors.logError(err);
}
// the src for the image must be in URI format, not a file system path, which in Windows uses \
var src = path.join('/', target_path).replace(new RegExp('\\' + path.sep, 'g'), '/');
return res.send(src);
});
});
});
}

View File

@ -47,12 +47,14 @@ describe('Admin Controller', function() {
req.files.uploadimage.name = "IMAGE.jpg";
sinon.stub(fs, 'mkdirs').yields();
sinon.stub(fs, 'copy').yields();
sinon.stub(fs, 'unlink').yields();
sinon.stub(fs, 'exists').yields(false);
});
afterEach(function() {
fs.mkdirs.restore();
fs.copy.restore();
fs.unlink.restore();
fs.exists.restore();
clock.restore();
});
@ -141,6 +143,17 @@ describe('Admin Controller', function() {
return admin.uploader(req, res);
});
it('should not leave temporary file when uploading', function(done) {
clock = sinon.useFakeTimers(new Date(2013, 8, 8, 10, 57).getTime());
sinon.stub(res, 'send', function(data) {
fs.unlink.calledOnce.should.be.true;
fs.unlink.args[0][0].should.equal('/tmp/TMPFILEID');
return done();
});
admin.uploader(req, res);
});
});
});
});