如何将文件上传到AWS中的预签名URL?

时间:2018-08-03 21:28:27

标签: javascript amazon-web-services aws-device-farm pre-signed-url

问题

我有一个来自AWS的预签名URL。我需要上传文件。我该怎么做?

(我必须使用预先签名的URL。我叫createUpload API for Device Farm,它返回一个。)

AWS Documentation gives examples on how to do this in Java, .NET and Ruby。缺少JavaScript。

尝试1

我改了示例here

const axios = require('axios');
const FormData = require('form-data');

function uploadFile(url, file) {
    if (typeof url !== 'string') {
        throw new TypeError(`Expected a string, got ${typeof url}`);
    }
    const formData = new FormData();
    formData.append(file,file)
    const config = {
        headers: {
            'content-type': 'multipart/form-data'
        }
    }
    return  axios.post(url, formData,config)
}

但是我收到此错误:

  

我们计算出的请求签名与您提供的签名不匹配。检查您的密钥和签名方法。

尝试2

我使用了cURL。但是,我不想依赖cURL。

const Promise = require('bluebird');
const cmd = require('node-cmd');
const getAsync = Promise.promisify(cmd.get, { multiArgs: true, context: cmd }); 

async function uploadFile(url, fileName) { 
    await throwIfCurlNotInstalled();
    console.log('uploadFile: Uploading file', {
        fileName
    });
    const command = `curl -T ${fileName} "${url}"`;
    try {
        let result = await getAsync(command);
        result.forEach(line => console.log(line));
        console.log('uploadFile: File uploaded', {
            fileName,
        });
    } catch (e) {
        console.error('uploadFile: Error uploading file', {
            fileName
        });
        console.error(e);
    }
}
async function throwIfCurlNotInstalled() {
    try {
        await getAsync(`curl -V`);
    } catch (e) {
        throw 'curl is not installed';
    }
}

1 个答案:

答案 0 :(得分:2)

解决方案非常简单:

const rp = require('request-promise');
const fs = require('fs');

async function uploadFile(url, fileName) {
    let options = {
        method: 'PUT',
        uri: url,
        body: fs.readFileSync(fileName),
    };

    return rp(options);
}