@@ -3,8 +3,6 @@ import { Readable, PassThrough } from "stream";
33import { HTTPError , ReadError , RequestError } from "./exceptions" ;
44import * as fileType from "file-type" ;
55
6- const fileTypeStream = require ( "file-type-stream" ) . default ;
7-
86const pkg = require ( "../package.json" ) ;
97
108function wrapError ( err : AxiosError ) {
@@ -59,27 +57,30 @@ export function postBinary(
5957 data : Buffer | Readable ,
6058 contentType ?: string ,
6159) : Promise < any > {
62- let contentTypeGetter ;
63- if ( contentType ) {
64- contentTypeGetter = Promise . resolve ( contentType ) ;
65- } else if ( Buffer . isBuffer ( data ) ) {
66- contentTypeGetter = Promise . resolve ( fileType ( data ) . mime ) ;
60+ let getBuffer : Promise < Buffer > ;
61+
62+ if ( Buffer . isBuffer ( data ) ) {
63+ getBuffer = Promise . resolve ( data ) ;
6764 } else {
68- contentTypeGetter = new Promise ( resolve => {
65+ getBuffer = new Promise ( ( resolve , reject ) => {
6966 if ( data instanceof Readable ) {
70- const passThrough = new PassThrough ( ) ;
71- data
72- . pipe ( fileTypeStream ( ( result : any ) => resolve ( result . mime ) ) )
73- . pipe ( passThrough ) ;
74- data = passThrough ;
67+ const buffers : Buffer [ ] = [ ] ;
68+ let size = 0 ;
69+ data . on ( "data" , ( chunk : Buffer ) => {
70+ buffers . push ( chunk ) ;
71+ size += chunk . length ;
72+ } ) ;
73+ data . on ( "end" , ( ) => resolve ( Buffer . concat ( buffers , size ) ) ) ;
74+ data . on ( "error" , reject ) ;
7575 } else {
76- throw new Error ( "invalid data type for postBinary" ) ;
76+ reject ( new Error ( "invalid data type for postBinary" ) ) ;
7777 }
7878 } ) ;
7979 }
8080
81- return contentTypeGetter . then ( ( contentType : string ) => {
82- headers [ "Content-Type" ] = contentType ;
81+ return getBuffer . then ( data => {
82+ headers [ "Content-Type" ] = contentType || fileType ( data ) . mime ;
83+ headers [ "Content-Length" ] = data . length ;
8384 headers [ "User-Agent" ] = userAgent ;
8485 return axios
8586 . post ( url , data , { headers } )
0 commit comments