我正在尝试将文件直接上传到S3存储桶,而没有后端。我可以部分获得签名和已签名的请求,但收到CORS错误。我已经启用了S3存储桶中的所有CORS,但是代码似乎相同。
这是代码...
import React, { Component } from 'react';
import fetch from 'isomorphic-unfetch';
import AWS from 'aws-sdk';
import FormData from 'form-data';
class Issues extends Component {
constructor(props) {
super(props);
this.state = {
file: [],
};
}
// Perform S3 signature generation
s3Signature = (file) => {
return new Promise((resolve, reject) => {
const s3 = new AWS.S3({accessKeyId: 'XXXXXXXXXXXXXXXXXX',
secretAccessKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
endpoint: 's3-eu-central-1.amazonaws.com',
region: 'eu-central-1'});
const myBucket = 'bucket-1';
const fileName = file.name;
const fileType = file.type;
const params = {
Bucket: myBucket,
Fields: {
key: file.name
},
Conditions: [
['content-length-range', 0, 10000000], // 10 Mb
{'acl': 'public-read'}
]
};
s3.createPresignedPost(params, function(err, data) {
if (err) {
console.error('Presigning post data encountered an error', err);
} else {
resolve(data);
}
});
});
}
sendFile = (file, payload) => {
var foo = document.getElementById('form');
var form = new FormData(foo);
form.append('acl', 'public-read');
form.append('Access-Control-Allow-Origin', '*');
for(const field in payload.fields) {
// console.log(field+'=>'+payload.fields[field]);
form.append(field, payload.fields[field]);
}
form.append('file', file)
fetch(payload.url, {
method: 'PUT',
body: form,
headers: {
'Access-Control-Allow-Origin': '*',
}
})
.then((response) => {
console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
return response.text();
})
.then((payload) => {
console.log(payload);
})
.catch((err) => console.log(`Error: ${err}`));
};
handleFormSubmit = (event) => {
event.preventDefault();
console.log(event);
console.log(this.state.file)
const fileName = this.state.file.name
this.s3Signature(this.state.file).then((payload) => { this.sendFile(this.state.file, payload); });
}
onChangeHandler = (event) => {
this.setState({file: event.target.files[0]})
}
render() {
return (
<div>
<form id='form' method='post' onSubmit={this.handleFormSubmit.bind(this)}>
<input type="file" name="file" onChange={this.onChangeHandler}/>
<input type="submit" value="Submit" />
</form>
</div>
);
}
export default Issues;
跨源请求被阻止:同源策略禁止阅读 位于的远程资源 https://s3-eu-central-1.amazonaws.com/ BUCKET_NAME(原因: CORS标头“ Access-Control-Allow-Origin”丢失)。
错误:TypeError:尝试获取资源时出现NetworkError。 issues.js:83(来自S3)