簡體   English   中英

使用 axios 將圖像上傳到 AWS 預簽名帖子 URL

[英]Uploading Image to AWS presigned post URL using axios

我正在嘗試使用在 Python 上使用 boto3 生成的預簽名 URL 將圖像上傳到 S3 存儲桶。我一直在使用文檔中提供的示例 python 代碼並成功(圖像已使用正確的內容類型正確上傳). 但是,當為了我們的前端應用程序而嘗試在 Javascript 中執行此操作時,我真的很難讓它工作。

這是后端返回的示例字典:

{
    "fields": {
        "AWSAccessKeyId": "AKIAYS3VM3EBIFL7FKE5",
        "key": "posts/623255a762fd9bdfbd13f91a",
        "policy": "<very long string>",
        "signature": "Qvc/sGBHk0uzirzIfR1YmE2kFlo="
    },
    "url": "https://hotspot-storage.s3.amazonaws.com/"
}

這是正常運行的 Python 代碼:

response = <json response object>
object_name = 'playground/example_profile_group.png'

response['fields']['Content-Type'] = "image/png"
# Demonstrate how another Python program can use the presigned URL to upload a file
with open(object_name, 'rb') as f:
    files = {'file': (object_name, f)}
    http_response = requests.post(response['url'], data=response['fields'], files=files)

# If successful, returns HTTP status code 204
print(http_response)
print(http_response.text)

這是無法運行的 Javascript 代碼:

const data = response.data;
let payload = data.fields;
payload['Content-Type'] = 'image/jpeg';
const file = {
    uri: previewPath,
    name: previewPath,
    type: 'image/jpeg',
};
payload.file = file;
const url = data.url;

console.log(payload, "MY PAYLOAD")

axios({
    method: 'post',
    headers: {'Content-Type': 'multipart/form-data'},
    url: url,
    data: payload,
})
    .then(function (response) {
    console.log(response.data, 'uploaded');
    const data = response.data;
    })
    .catch(function (error) {
    console.log(
        'error uploading image',
        error.response.data,
    );
    });
})
.catch(function (error) {
console.log(
    'error getting media link',
    error.response.data,
);
});

這是不斷返回的錯誤:

 error uploading image <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>MalformedPOSTRequest</Code><Message>The body of your POST request is not well-formed multipart/form-data.</Message><RequestId>Q0ES6P4QP75YVVED</RequestId><HostId>eowLxSJQD1xP1EfHPnzGSJzXVGpPjurIMhkdwAD22JMvi9zRoFGg6Bq+mnUt/Lu7DNPY80iBDMc=</HostId></Error>

我在這上面停留了很長一段時間,無法說出我做錯了什么。 任何幫助將不勝感激。

為了發送multipart/form-data請求主體,您需要使用FormData實例而不是 JavaScript object。

例如

const { url, fields } = response.data;
const payload = new FormData();
payload.append("file", file); // this is the file blob, eg from <input type="file">
payload.append("Content-Type", "image/jpeg");

// add all the other fields
Object.entries(fields).forEach(([ key, val ]) => {
  payload.append(key, val);
});

// No need to manually set content-type header, your browser knows what to do
const { data: result } = await axios.post(url, payload);
console.log("uploaded", result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM