下载然后上传图像而不存储它

Download then upload image without storing it

我目前正在尝试使用 Zapier 内置的图片上传组件,但在使用时遇到了问题。我必须能够下载一个图像,然后 POST 它到一个新的端点而不在本地存储它。目前,我能做的最接近的事情是将 IncomingMessage 发送到 POST,但我知道那是不对的。

有人有什么建议吗?

let FormData = require('form-data');
let http = require('https');

const makeDownloadStream = (url) => {
  new Promise((resolve, reject) => {
    http.request(url, resolve).on('error', reject).end();
  });
}

const makeUploadStream = (z, bundle, options) => {
    var imageRequest = options;
    const promise = z.request(imageRequest);
    return promise.then((response) => {
        return response.data;
    });
}

const addAttachment = async (z, bundle) => {
    /*var request = {
        'url': bundle.inputData.attachment
    };
    const promiseAt = z.request(request);
    return promiseAt.then((stream) => {*/
        const form = new FormData();
        var data = `{"type": "records", "attributes": {"form_id": ${bundle.inputData.form_id}}}`
        const stream = await makeDownloadStream(bundle.inputData.attachment);
        form.append(`field_${bundle.inputData.field_id}`, stream);
        form.append('data', data);
        var request = {
            'url': bundle.inputData.url,
            'method': 'PUT',
            'headers': {
                'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`
            },
            'body': form
        };
        const response = await makeUploadStream(z, bundle, request);
        return response;
    //});
}

我自己想出来了。对于任何需要在 Zapier 上上传图片的人,这里是:

let FormData = require('form-data');

const makeDownloadStream = (z, bundle) => {
    var imageRequest = {
        'url': bundle.inputData.attachment,
        'method': 'GET',
        'raw': true
    };
    const promise = z.request(imageRequest);
    return promise.then(async (response) => {
        var buffer = await response.buffer();
        return {
            'content-type': response.headers.get('content-type'),
            'content': buffer,
            'filename': response.headers.get('content-disposition').replace('attachment; filename="', '').replace('"', '')
        }
    });
}

const addAttachment = async (z, bundle) => {
    const form = new FormData();
    const content = await makeDownloadStream(z, bundle);
    form.append(`field_${bundle.inputData.field_id}`, Buffer.from(content.content.toString('binary'), 'binary'), {
        filename: content.filename
    });
    const request = {
        'url': `${bundle.inputData.url}/api/records/${bundle.inputData.record_id}`,
        'method': 'PUT',
        'headers': {
            'Content-Type': `multipart/form-data; boundary=${form.getBoundary()}`,
            'Content-Length': form.getLengthSync()
        },
        'body': form
    };
    const promise = z.request(request);
    return promise.then((response) => {
        return response.data;
    });
}