No Description

index.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. const http = require('http')
  2. const fs = require('fs')
  3. const path = require('path')
  4. const url = require('url')
  5. const formidable = require('formidable')
  6. const mimeTypes = {
  7. 'jpeg': 'image/jpeg',
  8. 'jpg': 'image/jpeg',
  9. 'png': 'image/png',
  10. 'svg': 'image/svg',
  11. 'gif': 'image/gif',
  12. 'mp4': 'video/mp4',
  13. 'mp3': 'audio/mp3'
  14. }
  15. const port = 9090
  16. const fileSaveDir = path.join(__dirname, 'temp')
  17. const uploadServer = (req, res) => {
  18. !fs.existsSync(fileSaveDir) && fs.mkdirSync(fileSaveDir)
  19. let responseData = []
  20. const form = new formidable.IncomingForm()
  21. form.uploadDir = fileSaveDir
  22. form.type = true
  23. form.keepExtensions = true
  24. form.parse(req, function(err, fields, files){
  25. if(!err) {
  26. Object.keys(files).forEach(function(key){
  27. const file = files[key]
  28. const filename = path.basename(file.path)
  29. // 塞入响应数据中
  30. responseData.push({
  31. type: file.type,
  32. name: filename,
  33. url: 'http://localhost:' + port + '/temp/' + filename,
  34. size: file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + 'MB' : ~~(file.size / 1024) + 'KB'
  35. })
  36. })
  37. } else {
  38. // console.warn(err)
  39. }
  40. res.setHeader('Access-Control-Allow-Origin', '*')
  41. res.writeHead(200)
  42. res.end(JSON.stringify(responseData))
  43. })
  44. }
  45. const staticServer = (req, res) => {
  46. var uri = url.parse(req.url).pathname
  47. var filename = path.join(process.cwd(), unescape(uri))
  48. var stats
  49. try {
  50. stats = fs.lstatSync(filename) // throws if path doesn't exist
  51. } catch (e) {
  52. res.writeHead(404, {'Content-Type': 'text/plain'})
  53. res.write('404 Not Found\n')
  54. res.end()
  55. return
  56. }
  57. if (stats.isFile()) {
  58. // path exists, is a file
  59. var mimeType = mimeTypes[path.extname(filename).split('.').reverse()[0]]
  60. res.writeHead(200, {'Content-Type': mimeType} )
  61. var fileStream = fs.createReadStream(filename)
  62. fileStream.pipe(res)
  63. } else if (stats.isDirectory()) {
  64. // path exists, is a directory
  65. res.writeHead(200, {'Content-Type': 'text/plain'})
  66. res.write('Index of '+uri+'\n')
  67. res.write('TODO, show index?\n')
  68. res.end()
  69. } else {
  70. // Symbolic link, other?
  71. // TODO: follow symlinks? security?
  72. res.writeHead(500, {'Content-Type': 'text/plain'})
  73. res.write('500 Internal server error\n')
  74. res.end()
  75. }
  76. }
  77. const server = http.createServer((req, res) => {
  78. if (req.method.toLowerCase() === 'get') {
  79. staticServer(req, res)
  80. } else {
  81. uploadServer(req, res)
  82. }
  83. })
  84. server.listen(port)