diff --git a/src/superagent.js b/src/superagent.js index a6b6af39a..a3f0d5ccc 100644 --- a/src/superagent.js +++ b/src/superagent.js @@ -190,11 +190,12 @@ class Request { return this; } - attach(name, filepath) { // this is only used in tests and thus simplistic + attach(name, filepathOrBuffer) { // this is only used in tests and thus simplistic if (!this.#boundary) this.#boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2); - const partHeader = Buffer.from(`--${this.#boundary}\r\nContent-Disposition: form-data; name="${name}" filename="${path.basename(filepath)}"\r\n\r\n`, 'utf8'); - const partData = fs.readFileSync(filepath); + const filename = Buffer.isBuffer(filepathOrBuffer) ? name : path.basename(filepathOrBuffer); + const partHeader = Buffer.from(`--${this.#boundary}\r\nContent-Disposition: form-data; name="${name}" filename="${filename}"\r\n\r\n`, 'utf8'); + const partData = Buffer.isBuffer(filepathOrBuffer) ? filepathOrBuffer : fs.readFileSync(filepathOrBuffer); this.#body = Buffer.concat([this.#body, partHeader, partData, Buffer.from('\r\n', 'utf8')]); return this;