Как разобрать POST-запрос с файлами в NodeJS?С и без сторонних библиотек - PullRequest
0 голосов
/ 30 мая 2019

Я пытался отправить файл на другой сервер для сохранения там, но я не знаю, как получить файл readstream из запроса.Я предполагаю, что это должно быть как прокси, но я не мог сделать это.


Я хочу понять, как я могу проанализировать POST-запрос с файлами

Я пробовал multer как в Custom StorageНапример, в своем документе, но затем я столкнулся с проблемой, как отправить его в другое место,

Я обнаружил, что модуль «request» npm может создать потоковый запрос на другой сервер, я попробовал, и яполучили ошибку в целевом сервере с multer.


Контроллер сервера, который должен сохранять мой файл:

export class UploadController {
    public uploadAndSaveFile(req: Request, res: Response, next: NextFunction) {
        upload.single('file')(req, res, (err: any) => {
           if (err) {
               console.error(err);
               return;
           }
        });

        if (!req.file) {
            res.sendStatus(400);
            console.log('not');
            return;
        }

        const filePath = req.file.path;
        const fileName = req.file.filename;
        const mimeType = req.file.mimetype;

        uploadService.create(filePath, fileName, mimeType)
            .then((fileModel: any) => res.send(fileModel.recordset))
            .catch(next);
    }
}

Пробовал с несколькими участниками

const form = new multiparty.Form();
        form.on('part', (part: any) => {
            request.post(`${config.get('services:StorageService')}/api/v1/upload`, {
                form: {
                    file: part
                }
            });
        });

Пробовал с multer:

StorageStream.prototype._handleFile = function _handleFile(req, file, cb) {
    this.getDestination(req, file, function (err, path) {
        if (err) return cb(err);


        request.post({
            url: `${config.get('services:StorageService')}/api/v1/upload`,
            formData: {
                file: file.stream,
            }
        }, (err: any, res: any, body: any) => {
            if (err) {
                logger.error(err);
                return;
            }

            console.log(body);
        })
    });
};
...