簡體   English   中英

使用 ReactJs 將大文件(視頻)上傳到 nodejs 服務器和 aws s3

[英]Upload Large file (Video) to nodejs server and aws s3 using ReactJs

我正在構建一個 OTT 平台,但在將大文件上傳到服務器時遇到問題。 我嘗試使用 multer 將文件存儲在臨時文件夾中並使用aws-sdk s3.upload 它適用於小文件大小,但如果我嘗試上傳大文件,它會返回

網絡錯誤或錯誤 413 請求實體太大

以下錯誤 413 - 我已更改 nginx.config ( client_max_body_size 0; )

// 0 代表無限

但仍然沒有變化。 我也試過用 multer-s3 來做,但仍然沒有成功。 后來我嘗試和busboy一起做,但我仍然面臨同樣的問題。 在這里,我在 ReactJs 中附加我的代碼,我正在使用 Axios 請幫助

服務器.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const passport = require('passport');
const helmet = require('helmet');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
const dotenv = require('dotenv');
// var admin = require('firebase-admin');
const rateLimit = require('express-rate-limit');
const busboy = require('connect-busboy');




const { setCloudinary } = require('./middleware/cloudinary');
// initalizing app
const app = express();

app.use(cors());
// app.use(helmet());
app.use(
  busboy({
    highWaterMark: 10 * 1024 * 1024, // Set 10 MiB buffer
  })
); // Insert the busboy middle-ware

// for environment files
if (process.env.NODE_ENV === 'production') {
  dotenv.config({ path: './env/.env.production' });
} else {
  dotenv.config({ path: './env/.env' });
}

const PORT = process.env.PORT || 5000;
const mongoDbUrl = process.env.mongoDbUrl;

const profileRoute = require('./routes/profile');
const adminRoute = require('./routes/admin');
const planRoute = require('./routes/plan');
const videoRoute = require('./routes/video');

//connnecting mongoDB server
mongoose
  .connect(mongoDbUrl, {
    useNewUrlParser: true,
    useFindAndModify: false,
    useCreateIndex: true,
    useUnifiedTopology: true,
  })
  .then((result) => {
    if (result) {
      setCloudinary();
      //if all goes right then listing to the server
      // var server = https.createServer(options, app);
      // console.log(server);
      app.listen(PORT, (err) => {
        if (err) throw err;
        console.log(`server is running at ${PORT}`);
      });
    }
  })
  .catch((err) => {
    throw err;
  });

//logging logs
if (process.env.NODE_ENV === 'production') {
  app.use(morgan('tiny'));
} else {
  app.use(morgan('dev'));
  mongoose.set('debug', true);
}

//initiallizaing passport
app.use(passport.initialize());
// require('./utils/adminRole')(passport);
require('./utils/firebase');
require('./utils/gcm');

app.use(express.json());
app.use(
  express.urlencoded({
    extended: true,
  })
);

// API serving routes
app.use('/api/v1/profile', profileRoute);
app.use('/api/v1/admin', adminRoute);
app.use('/api/v1/plan', planRoute);
app.use('/api/v1/videos', videoRoute);
// FOR REACT JS APP
//if the app is in production then serve files also
// if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
app.use(express.static(path.join(__dirname, 'client', 'build')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'));
});
// }

// task

require('./jobs/Jobs');

路由器.js

router.post('/add/video', (req, res) => {
  req.pipe(req.busboy); // Pipe it trough busboy

  req.busboy.on('file', (fieldname = 'video', file, filename) => {
    console.log(`Upload of '${filename}' started`);

    // Create a write stream of the new file
    const fstream = fs.createWriteStream(path.join('temp/', filename));
    // Pipe it trough
    file.pipe(fstream);

    // On finish of the upload
    fstream.on('close', () => {
      console.log(`Upload of '${filename}' finished`);

      const childProcess = fork('./processVideo.js', ['message']);
      childProcess.on('message', (msg) => res.send(msg));
      childProcess.send({ file: fstream, data: req.body });
    });
  });
});

在 ReactJs 我使用 Axios

 const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: function (progressEvent) {
        var percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        console.log(percentCompleted);
      },
    };
    const formData = new FormData();
    formData.append('video', selectedVideo);
    formData.append('title', title);
    formData.append('description', description);
    formData.append('movieCategory', movieCategory);
    formData.append('thumbnail', thumbnail);
    formData.append('price', price);
    formData.append('isPremium', isPremium);
    formData.append('quality', quality);
    formData.append('language', language);
    formData.append('releaseYear', releaseYear);
    formData.append('duration', duration);

    axios
      .post('/api/v1/admin/add/video', formData, config)
      .then((res) => {
        console.log(res);
        alert('File Upload success');
      })
      .catch((err) => {
        console.log(err);
        alert('File Upload Error');
      });

我建議您使用預簽名的S3 上傳鏈接。 在這種情況下,服務器只負責返回預簽名的上傳鏈接,並且從客戶端代碼直接將文件上傳到 AWS S3。

您是否嘗試過使用S3 多部分上傳或可能傳輸加速器r?

我看到你正在使用Express 您需要設置 Express 請求限制大小。 默認值為100kb

app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));

此外,Multer 也有默認文件大小限制為1mb ,所以也嘗試改變它:

const video_upload = multer({ 
  storage: videoStorage,
  fileFilter: videoFilter,
  limits: {
     fieldSize: '50mb'
  }
});

我使用多線程文件上傳解決了這個問題。 您可以在博客中了解它。 這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM