attachment.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. module.exports = function(crowi, app) {
  2. 'use strict';
  3. var debug = require('debug')('crowi:routs:attachment')
  4. , Attachment = crowi.model('Attachment')
  5. , User = crowi.model('User')
  6. , fs = require('fs')
  7. , actions = {}
  8. , api = {};
  9. actions.api = api;
  10. api.list = function(req, res){
  11. var id = req.params.pageId;
  12. Attachment.getListByPageId(id)
  13. .then(function(attachments) {
  14. res.json({
  15. status: true,
  16. data: {
  17. attachments: attachments
  18. }
  19. });
  20. });
  21. };
  22. /**
  23. *
  24. */
  25. api.add = function(req, res){
  26. var id = req.params.pageId;
  27. if (id == 0) {
  28. // TODO create page before process upload
  29. }
  30. var fileUploader = require('../util/fileUploader')(crowi, app);
  31. var tmpFile = req.files.file || null;
  32. if (!tmpFile) {
  33. return res.json({
  34. status: false,
  35. message: 'File error.'
  36. });
  37. }
  38. var tmpPath = tmpFile.path,
  39. fileName = tmpFile.name,
  40. fileType = tmpFile.mimetype,
  41. filePath = Attachment.createAttachmentFilePath(id, fileName, fileType);
  42. fileUploader.uploadFile(
  43. filePath,
  44. fileType,
  45. fs.createReadStream(tmpPath, {
  46. flags: 'r',
  47. encoding: null,
  48. fd: null,
  49. mode: '0666',
  50. autoClose: true
  51. }),
  52. {})
  53. .then(function(data) {
  54. Attachment.create(id, req.user, filePath, fileName, fileType)
  55. .then(function(data) {
  56. debug('Succesfully save attachment data', data);
  57. var imageUrl = fileUploader.generateS3FileUrl(data.filePath);
  58. return res.json({
  59. status: true,
  60. filename: imageUrl,
  61. attachment: data,
  62. message: 'Successfully uploaded.',
  63. });
  64. }, function (err) {
  65. debug('Error on saving attachment data', err);
  66. return res.json({
  67. status: false,
  68. message: '',
  69. });
  70. }).finally(function() {
  71. fs.unlink(tmpPath, function (err) {
  72. if (err) {
  73. debug('Error while deleting tmp file.');
  74. }
  75. });
  76. });
  77. }, function(err) {
  78. debug('Upload error to S3.', err);
  79. return res.json({
  80. status: false,
  81. message: 'Error while uploading.',
  82. });
  83. });
  84. };
  85. api.remove = function(req, res){
  86. var id = req.params.id;
  87. };
  88. return actions;
  89. };