【问题标题】:How do I upload a file to a pre-signed URL in AWS?如何将文件上传到 AWS 中的预签名 URL?
【发布时间】:2019-01-11 19:10:41
【问题描述】:

问题

我有一个来自 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';
    }
}

【问题讨论】:

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


    【解决方案1】:

    解决方案非常简单:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2019-08-05
      • 2022-01-27
      • 1970-01-01
      相关资源
      最近更新 更多