/*
 * @Author: jukaifeng jukaifeng@lingtu.com
 * @Date: 2024-10-24 09:00:33
 * @LastEditors: jukaifeng jukaifeng@lingtu.com
 * @LastEditTime: 2024-10-24 13:52:24
 * @FilePath: /case-uploads/server/index.js
 * @Description: 
 */
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const { writeFileSync } = require('fs');
const { resolve } = require('path');

const app = express();
app.use(bodyParser.json({ limit: '50mb' }));


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const ext = file.originalname.split('.').pop();
    cb(null, file.originalname + '-' + Date.now()) + '.' + ext;
  }
});
const upload = multer({ storage });


app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, x-ext');
  res.header('Access-Control-Allow-Methods', 'PUT, POST');
  next();
});



// multipart/form-data上传模式
app.post('/upload', upload.single('file'), (req, res) => {
  if (req.file) {
    res.send({
      code: 'success'
    });
  } else {
    res.send({
      code: 'error'
    });
  }
});


// base64上传模式
app.post('/base64', (req, res) => {
  const { file, ext } = req.body;
  const binaryData = Buffer.from(file, 'base64');

  writeFileSync(resolve(__dirname, `uploads/${Date.now()}.${ext}`), binaryData, 'binary');
  res.send({
    code: 'success'
  });
});


// 二进制上传模式
app.post('/binary', (req, res) => {
  const ext = req.headers['x-ext'];
  const buffers = [];
  req.on('data', (chunk) => {
    buffers.push(chunk);
  }).on('end', () => {
    const binaryData = Buffer.concat(buffers);
    writeFileSync(resolve(__dirname, `uploads/${Date.now()}.${ext}`), binaryData);
    res.send({
      code: 'success'
    });
  });
});


app.listen(3000, () => {
  console.log('Server is running on port 3000');
});