• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 이미지 업로드 관련 질문입니다

이미지 업로드 관련 질문입니다

  • 이 주제에는 3개 답변, 2명 참여가 있으며 codingapple1 년 전에 전에 마지막으로 업데이트했습니다.
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 글쓴이
  • #126263

    J
    참가자
    안녕하세요
    mongodb를 이용해서 이미지를 업로드하는데 이상하게 되서 문의드립니다
    클라이언트 는 react로 했습니다
    문제가 된것은 이미지를 여러개 첨부할때 일어납니다
    //NewPost.jsx
                  <form onSubmit={handleSubmit}>
                    <div style={{ marginBottom: "0.2rem" }}>
                      {" "}
                      <S.InputDiv>
                        <textarea
                          type="text"
                          name="PostContent"
                          rows={"4"}
                          placeholder="무슨 생각을 하고 계신가요?"
                        ></textarea>
                      </S.InputDiv>
                    </div>
                    <div>
                      <div style={{ marginBottom: "1rem" }}>모든사람이</div>
                      <div style={{ display: "flex", marginBottom: "0.2rem" }}>
                        <S.SubBtnDiv>
                          <input
                            type="file"
                            style={{ display: "none" }}
                            ref={fileInputRef}
                            name="imageAdd"
                            multiple="multiple"
                            accept="image/*"
                          />
                          <div onClick={handleImageClick}>
                            <Image />
                          </div>
                          <Smile /> <Calendar />
                        </S.SubBtnDiv>
                        <div>
                          {" "}
                          <S.SubmitBtn type="submit">등록하기</S.SubmitBtn>{" "}
                        </div>
                      </div>
                    </div>
                  </form>
    post의 확장자를 cjs로 한것은 .js로 하는데 require 가 안먹혀서 cjs로 바꾸면 된다는걸 확인후 변경했씁니다
    //post.cjs
    router.post("", loginCheck, async (req, res) => {
      // upload.single("imageAdd")(req, res, async (err) => { 싱글은 하나만 array 여러개
      upload.array("imageAdd", 4)(req, res, async (err) => {
        if (err) return res.status(400).json({ message: "이미지 업로드 실패" });
        try {
          console.log("파일", req.files);
          const images = await req.files.map((file) => file.location);
          console.log("이미지", images);
          await db.collection("post").insertOne({
            postcontent: req.body.postcontent,
            writer: req.user.username,
            nickname: req.user.nickname,
            img: images, //이미지 주소
            date: new Date(),
          });
          res.status(200).json({ message: "게시글 등록 성공" });
        } catch (e) {
          console.log("에러발생", e);
        }
      });
    });
    //server.cjs
    app.use("/post", require("./src/routes/post.cjs"));
     
     
    console.log로 찍어가면서 확인했던것들입니다
    파일 [
      {
        fieldname: 'imageAdd',
        originalname: 'b18a109376e95441f6f51094bfe5c6647dae79a7785de64cabae01a8a247c4bb.webp',
        encoding: '7bit',
        mimetype: 'image/webp',
        size: 63514,
        bucket: 'junoforum1',
        key: '1718970847502',
        acl: 'private',
        contentType: 'application/octet-stream',
        contentDisposition: null,
        contentEncoding: null,
        storageClass: 'STANDARD',
        serverSideEncryption: null,
        metadata: undefined,
        location: 'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970847502',
        etag: '"2e3213267b3257798d50513dbd3f66aa"',
        versionId: undefined
      },
      {
        fieldname: 'imageAdd',
        originalname: 'download.png',
        encoding: '7bit',
        mimetype: 'image/png',
        size: 916,
        bucket: 'junoforum1',
        key: '1718970847502',
        acl: 'private',
        contentType: 'application/octet-stream',
        contentDisposition: null,
        contentEncoding: null,
        storageClass: 'STANDARD',
        serverSideEncryption: null,
        metadata: undefined,
        location: 'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970847502',
        etag: '"d0731e4a611922d9b733cdbea9f3d176"',
        versionId: undefined
      }
    ]
    이미지 [
      'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970847502',
      'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970847502'
    ]
    파일 [
      {
        fieldname: 'imageAdd',
        originalname: '312413.png',
        encoding: '7bit',
        mimetype: 'image/png',
        size: 3315,
        bucket: 'junoforum1',
        key: '1718970890454',
        acl: 'private',
        contentType: 'application/octet-stream',
        contentDisposition: null,
        contentEncoding: null,
        storageClass: 'STANDARD',
        serverSideEncryption: null,
        metadata: undefined,
        location: 'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970890454',
        etag: '"490d7317f84fc9b186a302d66af1f9d1"',
        versionId: undefined
      },
      {
        fieldname: 'imageAdd',
        originalname: 'download.png',
        encoding: '7bit',
        mimetype: 'image/png',
        size: 916,
        bucket: 'junoforum1',
        key: '1718970890454',
        acl: 'private',
        contentType: 'application/octet-stream',
        contentDisposition: null,
        contentEncoding: null,
        storageClass: 'STANDARD',
        serverSideEncryption: null,
        metadata: undefined,
        location: 'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970890454',
        etag: '"d0731e4a611922d9b733cdbea9f3d176"',
        versionId: undefined
      }
    ]
    이미지 [
      'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970890454',
      'https://junoforum1.s3.ap-northeast-2.amazonaws.com/1718970890454'
    ]
     
    각각 다른 이미지를 input에 넣고 전달하는것 까지는 지장이없는데
    mongodb에 저장할때 문제가 생깁니다
     
    문제를 못찾겠어서 문의를 드립니다 ..
    #126267

    codingapple
    키 마스터
    어떤게 안됩니까
    #126302

    J
    참가자
    아 이전에 문제가 이미지1, 이미지2를 올리면 클라이언트측에서는 이미지1 이미지2 둘다 전송한걸로보이는데
    s3에 저장후 이미지 주소 가져와서 몽고 db에 이미지 주소 저장할때 하나의 이미지주소를 2개 저장하는 문제가 있었습니다
    어제 질문글 올리고 혼자서 하나씩 찾아보니
    //middlewares.cjs
    const s3 = new S3Client({
      region: "ap-northeast-2",
      credentials: {
        accessKeyId: process.env.S3_KEY,
        secretAccessKey: process.env.S3_SECRET,
      },
    });
    const upload = multer({
      storage: multerS3({
        s3: s3,
        bucket: "junoforum1",
        key: function (요청, file, cb) {
          cb(null, Date.now().toString()); //업로드시 파일명 변경가능
        },
      }),
    });
    
    
    이부분이 문제였던거 같습니다  이미지를 각각 고유?한 키로 분류를 해줘야하는데
    날짜만 지정해줘서? 업로드할떄 날짜는 같으니까 같은걸로 인식한거같습니다
    //middlewares.cjs 수정후
    const upload = multer({
      storage: multerS3({
        s3: s3,
        bucket: "junoforum1",
        key: function (요청, file, cb) {
          // 랜덤 문자열 생성
          const randomBytes = crypto.randomBytes(8).toString("hex");
          // 현재 시간
          const now = Date.now().toString();
          // 파일의 원래 이름에서 확장자 추출
          const extension = file.originalname.split(".").pop();
          // 최종 파일명: 랜덤문자열_시간.확장자
          const finalFileName = `${randomBytes}_${now}.${extension}`;
          cb(null, finalFileName);
        },
      }),
    });
    
    
    이렇게 바꿔서 해결한거같긴한데 제대로된 방식이 맞는지요 ?
     
     
     
    #126318

    codingapple
    키 마스터
    넴 안겹치게 랜덤문자같은거 활용하면 됩니다
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠