![](/img/trans.png)
[英]What is the difference between Fetch & Axios when uploading an image to S3 bucket from the browser
[英]S3 creating empty files when uploading a file from React contact form using Axios
我創建了一個測試聯系表單,用戶可以在其中上傳圖片附件。
但是,在 S3 中,所有文件都顯示為空。 大小似乎會根據鏈接大小的長度而變化(例如,blob 是 63B,硬編碼鏈接的大小會有所不同),因此看起來它只是將鏈接作為數據,而不是實際圖像。 我檢查了很多次我的 axios 語法是否正確,並且在 SO 中經歷了許多線程,但無法弄清楚我做錯了什么。
AWS Lambda 生成預簽名的 URL:
const AWS = require('aws-sdk')
AWS.config.update({ region: 'eu-west-2' })
const s3 = new AWS.S3();
const uploadBucket = 'xxx-bucket'
exports.handler = async (event) => {
const result = await getUploadURL()
console.log('Result: ', result)
return result
};
const getUploadURL = async function() {
console.log('getUploadURL started')
let actionId = Date.now()
var s3Params = {
Bucket: uploadBucket,
Key: `${actionId}.jpg`,
ContentType: 'image/jpeg',
CacheControl: 'max-age=31104000',
ACL: 'public-read'
};
return new Promise((resolve, reject) => {
// Get signed URL
let uploadURL = s3.getSignedUrl('putObject', s3Params)
resolve({
"statusCode": 200,
"isBase64Encoded": false,
"headers": {
"Access-Control-Allow-Origin": "*"
},
"body": JSON.stringify({
"uploadURL": uploadURL,
"photoFilename": `${actionId}.jpg`
})
})
})
}
反應前端:
class QuoteForm extends Component {
constructor(props) {
super(props);
this.state = {
file:null,
};
};
onContactNameChange(e){
this.setState({ContactName:e.target.value});
};
onFileChange(e){
let [file] = e.target.files;
if (file) {
this.setState({
file: URL.createObjectURL(e.target.files[0]),
});
console.log(file);
}
};
async handleSubmit(e){
e.preventDefault();
axios.post(`https://xxxx/`)
.then(res => {
console.log(res)
const url = res.data.uploadURL;
const axiosConfig = {
headers: {
"Content-Type": "image/jpeg",
"Cache-Control": 'max-age=31104000'
}
}
axios.put(url, this.state.file, axiosConfig)
.then(response => {console.log(response)}).catch(err => {console.log(err.response)
});
});
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<input
type="file"
name="file"
id="fileUpload"
onChange={this.onFileChange.bind(this)}
/>
<img src={this.state.file} alt="img" />
<button
className="large"
style={{marginTop:"1.25rem"}} >
Submit
</button>
</form>
);
}
}
我只是不明白為什么 S3 存儲桶中的文件變成空的。
好的,我知道我的問題是什么。 我的前端 React 代碼中的createObjectURL
顯然不能用於將文件上傳到服務器,因為它實際上不包含該文件,但僅包含 URL。 我將整個onFileChange(e)
function 縮短為下面的,S3 開始接收實際文件。
onFileChange(e){
const [selectedFile] = e.target.files;
if (selectedFile) {
this.setState({file:selectedFile})
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.