반응형

express 환경에 multer 라이브러리를 이용해 간단히 구성 가능하다.

 

 

interface Multer {
        /**
         * Returns middleware that processes a single file associated with the
         * given form field.
         *
         * The `Request` object will be populated with a `file` object containing
         * information about the processed file.
         *
         * @param fieldName Name of the multipart form field to process.
         */
        single(fieldName: string): RequestHandler;
        /**
         * Returns middleware that processes multiple files sharing the same field
         * name.
         *
         * The `Request` object will be populated with a `files` array containing
         * an information object for each processed file.
         *
         * @param fieldName Shared name of the multipart form fields to process.
         * @param maxCount Optional. Maximum number of files to process. (default: Infinity)
         * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName`
         */
        array(fieldName: string, maxCount?: number): RequestHandler;
        /**
         * Returns middleware that processes multiple files associated with the
         * given form fields.
         *
         * The `Request` object will be populated with a `files` object which
         * maps each field name to an array of the associated file information
         * objects.
         *
         * @param fields Array of `Field` objects describing multipart form fields to process.
         * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` for any field.
         */
        fields(fields: ReadonlyArray<Field>): RequestHandler;
        /**
         * Returns middleware that processes all files contained in the multipart
         * request.
         *
         * The `Request` object will be populated with a `files` array containing
         * an information object for each processed file.
         */
        any(): RequestHandler;
        /**
         * Returns middleware that accepts only non-file multipart form fields.
         *
         * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if any file is encountered.
         */
        none(): RequestHandler;
    }

아래 3가지 함수를 주로쓴다.

 

single

- 한개의 파라미터에 대해서만 파싱해준다.

 

array

- array단위로 파라미터를 파싱해준다.

 

fields

- 파라미터명은 files 라는 이름이고, array형태로 값이 들어온다.

 

const app = express();
const storage = multer.memoryStorage();
const upload = multer({ 
    storage: storage,
    limits: {
        fileSize: 500 * 1024 * 1024, // Allow files up to 5MB
    }
});

app.post('/', upload.fields([{name: 'file'},{name: 'cover'}]), async (req, res) => {

})

 

cover와 file 파라미터 명으로 지정한값으로 파라미터를 받을 수있다.

반응형

+ Recent posts