简体   繁体   中英

How can I send file from a remote AWS S3 to Other Server Using AXIOS in NODE JS

Hello I am implementing an API endpoint where I can send a file coming from aws S3. What I have done is I get the file in from my s3 bucket

let file_data = await S3.getObject(params).promise();
let buf = Buffer.from(file_data.Body);

const file = buf.toString("base64");

Now I want to send the file to other API for verification purposes. I tried something like this but doesn't seems to work

var data = new FormData();

const data_file = fs.createReadStream(fs.createWriteStream(file));
data.append("document", data_file);

var config = {
    method: "post",
    url: `${process.env.URL}/verify_file`,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: `Bearer ${token}`,
        ...data.getHeaders(),
    },
    data: data,
};

try {
    const res = await axios(config);
    console.log(res.data);
} catch (error) {
    console.error("sendPassport", error);
}

I found my solution. I create a file from a buffer that I get from AWS S3. Then save it in my current working directory.

    let file_data = await S3.getObject(params).promise();

    const buffer = Buffer.from(file_data.Body, "utf8");
    // Create and download a file
    fs.writeFileSync(
                `${process.cwd()}/public/tmp/${data.filename}`,
                buffer
            );

Then I converted the file into stream using fs.createReadStream() function then send send the file

    var data = new FormData();

    const data_file = fs.createReadStream(`${process.cwd()}/public/tmp/${data.filename}`);

    data.append("document", data_file);

    var config = {
        method: "post",
        url: `${process.env.URL}/verify_file`,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            Authorization: `Bearer ${token}`,
            ...data.getHeaders(),
        },
        data: data,
    };

    try {
        const res = await axios(config);
        console.log(res.data);

    } catch (error) {
        console.error("sendPassport", error);
    }

    // Delete the file
    fs.unlinkSync(file_path);

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