简体   繁体   中英

change multer uploaded file to ReadStream

I'm using nestjs, multer to read uploaded files.

file is well uploade via POST rest api. I want to convert. this file to ReadableStream.

I want to avoid using write this files in disk and read again using createReadStream , it would be better convert direct to ReadableStream using uploaded meta infos.

export function ApiFile(fieldName: string) {
  return applyDecorators(UseInterceptors(FileInterceptor(fieldName)));
}
@Post("/file_upload")
@ApiFile('file')
  create(
    @Body() createNewsDto: CreateNewsDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    console.log({ file });
    return this.myService.create(createNewsDto, file);
  }

this is file meta data

{
  file: {
    fieldname: 'file',
    originalname: 'screenshot.png',
    encoding: '7bit',
    mimetype: 'image/png',
    buffer: <Buffer 59 10 4f 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 cf 00 00 02 1b 08 06 00 00 00 14 dd 73 8e 00 00 01 55 61 43 43 50 49 43 43 20 50 72 6f 66 69 ... 298432 more bytes>,
    size: 298982
  }
}

how can I achieve this?

I figured out how to send my files to remote server.

you need to use ReadableStream.from which change buffer file to ReadStream.

if your file meta info is below,

{
  file: {
    fieldname: 'file',
    originalname: 'screenshot.png',
    encoding: '7bit',
    mimetype: 'image/png',
    buffer: <Buffer 59 10 4f 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 cf 00 00 02 1b 08 06 00 00 00 14 dd 73 8e 00 00 01 55 61 43 43 50 49 43 43 20 50 72 6f 66 69 ... 298432 more bytes>,
    size: 298982
  }
}

you can convert this meta into stream

import { Readable} from 'stream';
import * as FormData from "form-data";

const formData = new FormData();
const stream = Readable.from(file.buffer);

formData.append("anyKeyValue", stream, {
  filename:  file.originalname,
  contentType: file.mimetype
})

then send to remote server with content type multipart/form-data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM