4

I'm trying to send a multipart/form-data image to another server, using unirest. Their .attach() works with a fs.createReadStream(), however, I have not been able to convert the buffer to an image. The logical step is to convert the buffer to Uint8Array first, then creating a read stream from it. However, this throws up an error message saying that the array must not contain null values. Removing 0 entries from the array will almost certainly break the image.

Image is not null, has all the bytes, and even sending the image data as a giant string works.

Here's what I tried:

    imageBytes = new Uint8Array(image.buffer)
    unirest
        .post(someURL)
        .headers(headers)
        .attach("image", fs.createReadStream(imageBytes))
        .end(response => {
            console.log(response.body);
        });

The alternatives are:
1. Attaching the buffer directly, which sends the raw data as a form field. Not ideal, and might run into image size restrictions.
2. Write the file to storage instead of keeping it in memory. This would be handling some sensitive information, thus would require auto-deletion post a certain amount of time, leading to more work.

EDIT: I ended up switching to request, as that allowed inline 'files' from buffers. The code to do so is below:

request({
        uri: someURL,
        method: "POST",
        formData: {
            "image": {
                value: image.buffer,
                options: {
                    filename: image.originalname,
                    contentType: image.mimetype
                }
            }
        }
    }, (err, resp, body) => {
        if (err) {
            console.log("ERROR -> " + err)
        }
        if (body) {
            console.log(body)
        }
    })

EDIT2: Please also put in encoding: null in the request options if you follow this. Don't be like me and spend a day tracking down why your returned data is of an alien format. :)

sk0g
  • 43
  • 6

0 Answers0