node.js에서 이미지 파일을 업로드하는 방법은 무엇입니까?

Sep 25 2020
 var title="this is title";
  var content="this is content";
  const config = { headers: {'Accept': 'application/json', 'Content-Type': 'multipart/form-data' } };
  const form = new FormData()
  let file =event.target.files[0]
  form.append('file', file)
 form.append('title', title)
   form.append('content', content)`enter code here`
Axios.post("http://localhost:3001/article/get/123", form,config ).then((res)=>{
     console.log(res.data)
   })

답변

1 NileshSolanki Sep 25 2020 at 17:54

노드에서 나는 이미지 또는 다른 것을 업로드하기 위해 multer를 사용했습니다.

아래는 제가 미들웨어로 사용한 업로드 코드입니다.

const util = require("util");
const path = require("path");
const multer = require("multer");

const storage = multer.diskStorage({ 
    destination: function (req, file, cb) {
        cb(null, "./Uploads") // folder path where to upload
    }, 
    filename: function (req, file, cb) { 
      cb(null, file.originalname + "-" + Date.now() + path.extname(file.originalname))
    } 
  });

const maxSize = 1 * 20000 * 20000; // file size validation

const uploadFiles = multer({ storage: storage, limits: { fileSize: maxSize } }).array("myfiles", 10); // key name should be myfiles in postman while upload

const uploadFilesMiddleware = util.promisify(uploadFiles);

module.exports = uploadFilesMiddleware;

다음은 업로드 및 파일 확인을 위해 컨트롤러에서 만든 기능입니다.

fileUpload = async (req, res) => {
  try {
        let userCode = req.headers.user_code;
        await upload(req, res);
        if (req.files.length <= 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Kindly select a file to upload..!!', true));
        }
        let response = [];
        for (const element of req.files) {
            let data =  await service.addFileData(element, userCode);
            response.push(data); // for file path to be stored in database
        }
        if (response && response.length > 0) {
            return res.status(httpStatusCode.OK).send(responseGenerators(response, httpStatusCode.OK, 'File uploaded sucessfully..!!', false));
        } else {
            return res.status(httpStatusCode.OK).send(responseGenerators({}, httpStatusCode.OK, 'Failed to upload file kindly try later..!!', true));
        }
      } catch (error) {
            logger.warn(`Error while fetch post data. Error: %j %s`, error, error)
            return res.status(httpStatusCode.INTERNAL_SERVER_ERROR).send(responseGenerators({}, httpStatusCode.INTERNAL_SERVER_ERROR, 'Error while uploading file data', true))
        }
    }

그리고 경로는 이렇게 갈 것입니다.

router.post('/upload/file', fileUploadController.fileUpload);

미들웨어에서와 같이 파일을 업로드하는 동안 우편 배달부에 동일한 이름을 유지해야합니다.

omair Sep 25 2020 at 17:29

위의 코드는 react.js에 있습니다. node.js에서 동일한 작업을 수행하고 파일이 공용 폴더에서 업로드됩니다. 가장 큰 문제는 우리가 프론트 엔드 event.target.files [0]에서와 같은 형식으로 이미지 파일을 업로드하는 방법입니다.