Файл 7 бит, закодированный из Angular, не создает буфер - PullRequest
0 голосов
/ 03 февраля 2020

Я пытаюсь изменить размер изображения на сервере Node с помощью Sharp, но нет файлового буфера, и поэтому я получаю сообщение об ошибке. Кодировка файла 7-битная, не должна ли она быть по умолчанию utf-8? В любом случае, как я могу создать буфер из этого изображения?

В Angular:

  onSavePost() {
    if (this.form.invalid) {
        return;
    }
    if (this.mode === 'create') {
        const post = new FormData();
        post.append('_id', undefined);
        post.append('title', this.form.value.title);
        post.append('content', this.form.value.content);
        post.append('image', this.form.value.image)
        post.append('author', this.author);
        post.append('group', this.groupId);

        this.store.dispatch(PostActions.createPost({ post }));
        this.store.dispatch(SpinnerActions.startSpinner());

    } else if (this.mode === 'edit') {
        let postData: Post | FormData;
        if (typeof this.form.value.image === 'object') {
            postData = new FormData();
            postData.append('_id', this.postId);
            postData.append('title', this.form.value.title);
            postData.append('content', this.form.value.content);
            postData.append('group', this.groupId);
            postData.append('image', this.form.value.image, this.form.value.title);
        } else {
            postData = {
                _id: this.postId,
                title: this.form.value.title,
                content: this.form.value.content,
                imagePath: this.form.value.image,
                group: this.groupId,
                author: null
            };
        }

    }
    this.form.reset();
    this.isLoading$ = true;
    this.router.navigate(['/groups', `${this.groupId}`]);
}

Узел промежуточного программного обеспечения:

const MIME_TYPE_MAP = {
    'image/png': 'png',
    'image/jpeg': 'jpg',
    'image/jpg': 'jpg'
};

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "backend/images");
    },
    fileFilter(req, file, next) {
        if (file.mimetype.startsWith('image/') && MIME_TYPE_MAP[file.mimetype]) {
            next(null, true);
        } else {
            next({ message: 'Filetype not allowed!' }, false);
        }
    }
});

const sortFile = multer({ storage }).single("image");

const resize = async (req, res, next) => {
    // check if there's a new file
    if (!req.file) {
        next();
        return;
    }
    const buffer = await sharp(req.file.buffer)
        .resize({
            width: 300,
            height: 300
        })
        .png()
        .toBuffer();
    req.file = buffer;
    next();
};

module.exports = { sortFile, resize }

req.file.buffer не определено.

Спасибо за вашу помощь.

...