sql >> Database >  >> NoSQL >> MongoDB

NodeJS Knox Formidable resulteert in een 400, bestand niet geüpload naar S3-bucket

Ik kreeg mijn code niet werkend met knox, ik kreeg steeds een 400 statusCode en mijn bestanden werden niet geüpload naar S3. Dus ik gebruikte aws-sdk en het werkte als magie. Mijn bestanden worden geüpload en opgeslagen in mijn Mongo-database. Voor degenen die hetzelfde probleem zouden kunnen tegenkomen, dit is wat ik deed:

const { config } = require("aws-sdk");

module.exports = (express, app, formidable, fs, os, gm, s3, mongoose, io) => {
  //os.tmpDir = os.tmpdir;
  let Socket;

  io.on("connection", function (socket) {
    Socket = socket;
  });

  const singleImage = new mongoose.Schema({
    filename: {
      type: String,
      require: true,
    },
    votes: {
      type: Number,
      require: true,
    },
  });

  let singleImageModel = mongoose.model("singleImage", singleImage);
  let router = express.Router();

  router.get("/", function (req, res, next) {
    res.render("index", { host: app.get("host") });
  });

  router.post("/upload", function (req, res, next) {
    // File upload

    function generateFilename(filename) {
      let ext_regex = /(?:\.([^.]+))?$/;
      let ext = ext_regex.exec(filename)[1];
      let date = new Date().getTime();
      let charBank = "abcdefghijklmnopqrstuvwxyz";
      let fstring = "";
      for (let i = 0; i < 15; i++) {
        fstring += charBank[parseInt(Math.random() * 26)];
      }
      return (fstring += date + "." + ext);
    }

    let tmpFile, nFile, fName;
    let newForm = new formidable.IncomingForm();
    newForm.keepExtensions = true;
    newForm.parse(req, function (err, fields, files) {
      tmpFile = files.upload.path;
      fName = generateFilename(files.upload.name);
      nFile = os.tmpDir() + "\\" + fName;
      res.writeHead(200, { "Content-type": "image/JPG" });
      res.end();
    });

    newForm.on("end", function () {
      fs.rename(tmpFile, nFile, function () {
        // Resize the image and upload this file into the S3 bucket
        gm(nFile)
          .resize(300)
          .write(nFile, function () {
            // Upload to the S3 Bucket
            /* fs.readFile(nFile, function (err, buf) {
              let req = knoxClient.put(fName, {
                "Content-Length": buf.length,
                "Content-Type": "image/JPG",
                "x-amz-acl": "public-read",
              }); */

            const fileContent = fs.readFileSync(nFile);

            const params = {
              Bucket: require("../config").S3Bucket,
              Key: fName,
              Body: fileContent,
            };

            s3.upload(params, function (err, data) {
              // Delete the Local file
              fs.unlink(nFile, function (err) {
                console.log("Local file deleted!");
                if (err) {
                  console.error(err);
                }
              });
              console.log("PRINT FILE: ", fName);
              if (err) {
                console.log("ERROR MSG: ", err);
                res.status(500).send(err);
              } else {
                //This means that the file is in the S3 Bucket
                console.log(fName + " is in the S3 bucket");

                let newImage = new singleImageModel({
                  filename: fName,
                  votes: 0,
                }).save();

                Socket.emit("status", { msg: "Saved!!", delay: 3000 });
                Socket.emit("doUpdate", {});

                res.status(200).end();
              }
            });

            /*               req.on("response", function (res) {
                if (res.statusCode == 200) {
                  

                } else {
                  console.log(
                    err +
                      fName +
                      " did not get to the database or S3 bucket so " +
                      nFile +
                      " was not deleted " +
                      res.statusCode
                  );
                  console.log(res.statusMessage);
                }
              }); */

            // req.end(buf);
            //     });
          });
      });
    });
  });

  app.use("/", router);
};




  1. Pizza Tribes - Een op browser gebaseerd realtime strategiespel voor meerdere spelers

  2. Een geneste array opvragen in MongoDb

  3. Hoe documenten filteren op basis van een embedded array?

  4. mongodb c# selecteer specifiek veld