Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
multiple kind of files for AWS + express -fileupload

so i've been trying to understand something with this. until now i could post images, but now i would like to add PDF's aswell. i don't get if i can just add 'pdf' to my content Type or if i have to do another new config?


  import AWS from "aws-sdk";

const s3 = new AWS.S3({
  accessKeyId: process.env.S3_ACCESS_KEY,
  secretAccessKey: process.env.S3_SECRET_KEY,
});

const buildObject = (key: string, body: string) => {
  return {
    Bucket: process.env.S3_BUCKET_NAME,
    Key: `${key}`,
    Body: body,
    ACL: "public-read",
    ContentEncoding: "base64",
    ContentType: "image/jpeg",
  };
};

export const upload = (fileData: string, options = { type: null }) => {
  let { type = "image/png" } = options;

  if (fileData.includes("base64") || !options.type) type = "image/jpeg";

  const file = `${new Date().getTime()}.${type.split("/")[1]}`;

  const object = buildObject(file, fileData);

  return new Promise((resolve, reject) => {
    s3.upload(object, (err, data) => {
      if (err) reject(err);
      else resolve(data.Location);
    });
  });
};



about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I believe you should use the Content-Type: "application/pdf".

I would advise using one lambda for images and another for pdfs to give it single responsibility.

You will need one type of request for images and another for pdfs.

about 4 years ago · Juan Pablo Isaza Relatório

0

the end result after many days of searching, it worked:

    export const uploadFileForTechnialReport = async (req, res) => {
      const { file } = req.files;
      const { mimetype } = file;
      const allowedTypes = ["jpeg", "jpg", "pdf"];

      try {
        if (!allowedTypes.some(type => mimetype.includes(type))) {
          return res.status(422).jsonp("Invalid format try with jpeg, jpg or PDF");
        }

        let url;

        console.log("start uploading to s3");
        switch (mimetype.split("/")[1]) {
          case "pdf":
            url = await uploadPDF(file.data);
            break;

          default:
            url = await upload(file.data);
            break;
        }
        console.log("upload to s3 done");

        return res.status(200).send(url);
      } catch (err) {
        return res.status(400).send(`AN_ERROR_OCCURED_${err}`);
      }
    };







const s3 = new AWS.S3({
  accessKeyId: process.env.S3_ACCESS_KEY,
  secretAccessKey: process.env.S3_SECRET_KEY,
});

const buildObject = (key: string, body: string) => {
  return {
    Bucket: process.env.S3_BUCKET_NAME,
    Key: `${key}`,
    Body: body,
    ACL: "public-read",
    ContentEncoding: "base64",
    ContentType: "image/jpeg",
  };
};

export const upload = (fileData: string, options = { type: null }) => {
  let { type = "image/png" } = options;

  if (fileData.includes("base64") || !options.type) type = "image/jpeg";

  const file = `${new Date().getTime()}.${type.split("/")[1]}`;

  const object = buildObject(file, fileData);

  return new Promise((resolve, reject) => {
    s3.upload(object, (err, data) => {
      if (err) reject(err);
      else resolve(data.Location);
    });
  });
};

const buildObjectPDF = (key: string, body: string) => {
  return {
    Bucket: process.env.S3_BUCKET_NAME,
    Key: `${key}`,
    Body: body,
    ACL: "public-read",
    ContentEncoding: "base64",
    ContentType: "application/pdf",
  };
};

export const uploadPDF = async (fileData: string, options = { type: null }) => {
  const file = `${new Date().getTime()}.pdf`;

  const object = buildObjectPDF(file, fileData);

  const { Location } = await s3.upload(object).promise();

  return Location;
};

export const deleteFile = () => {};

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda