我正在尝试将图像上传到Amazon S3,但始终收到此错误:“ VM222:1 Uncaught SyntaxError:JSON中位置0的意外令牌<”。我不确定该怎么办。我遵循了网站上的所有示例代码。我的代码写在下面。
const uploadFile = (file, signedRequest, url) => {
const xhr = new XMLHttpRequest();
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200){
document.getElementById('preview').src = url;
document.getElementById('avatar-url').value = url;
}
else{
alert('Could not upload file.');
}
}
};
xhr.send(file);
}
const getSignedRequest = (file) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', `/sign-s3?file-name=${file.name}&file-type=${file.type}`);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200){
const response = JSON.parse(xhr.responseText);
uploadFile(file, response.signedRequest, response.url);
}
else{
alert('Could not get signed URL.');
}
}
};
xhr.send();
}
const initUpload = () => {
const files = document.getElementById('file-input').files;
const file = files[0];
if(file == null){
return alert('No file selected.');
}
getSignedRequest(file);
}
return (
<div style={{ maxWidth: "700px", margin: "2rem auto" }}>
<div style={{ textAlign: "center", marginBottom: "2rem" }}>
<Title level={2}> Upload Prompt</Title>
</div>
<Form onSubmit={onSubmit}>
{/* DropZone */}
{/* <FileUpload refreshFunction={updateImages} /> */}
{/* kamran's code */}
<input type="file" id="file-input" onChange={initUpload}/>
非常感谢您的帮助。谢谢