app.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const express = require('express');
  2. const aws = require('aws-sdk');
  3. const multer = require('multer');
  4. const multerS3 = require('multer-s3');
  5. const path = require("path");
  6. const app = express();
  7. // 配置 AWS SDK
  8. const s3 = new aws.S3({
  9. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  10. secretAccessKey: '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',
  11. region:'cn-northwest-1'
  12. });
  13. // 配置 Multer 以处理文件上传
  14. const upload = multer({
  15. storage: multerS3({
  16. s3: s3,
  17. bucket: 'ccrb',
  18. acl: 'public-read', // 设置文件权限为公共读取
  19. key: function (req, file, cb) {
  20. cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname)); // 保存到S3时的文件名
  21. }
  22. })
  23. });
  24. // 接收文件上传的 POST 请求
  25. app.post('/img', upload.single('file'), (req, res) => {
  26. // console.log(req.file.location);
  27. res.json({ fileUrl: req.file.location }); // 返回上传后文件在S3中的URL
  28. });
  29. //app.use(router.routes()).use(router.allowedMethods());
  30. // 启动服务器
  31. const port = 7334;
  32. app.listen(port, () => {
  33. console.log(`Server is running on http://localhost:${port}`);
  34. });