我正在尝试使用reactjs上传图片,但图片上传到亚马逊s3时已损坏。 代码如下。
uploadToS3 = (imageUri, fileName, fileType, file,success, failure) => {
let body = new FormData();
let url=imageServer+fileName;
body.append('key', fileName);
body.append('acl', 'public-read');
body.append('Content-Type', 'multipart/form-data');
body.append('Content-Disposition', 'inline');
body.append('file', {
name: 'file',
uri: imageUri,
type: file.type
});
return axios.post(imageServer,body,
{ headers: {
'Accept':file.type,
'Content-Type':file.type,
}}
).then(response => {
console.log('[AWS S3] Response ==> ', response)
this.props.addNewImage(url,this.props.arrayname);
return response;
}).catch(error => {
console.log('[AWS S3] Error ==> ', error)
return error;
})
}
答案 0 :(得分:0)
实际上我犯的错误是在formData对象中为'file'对象发送了错误的值。正确的代码如下 -
uploadToS3 = (imageUri, fileName, fileType, file,success, failure) => {
let body = new FormData();
let url=imageServer+fileName;
body.append('acl', 'public-read');
body.append('Content-Type',file.type);
body.append('key', fileName);
body.append('file',file);
return axios.post(imageServer,body)
.then(response => {
console.log('[AWS S3] Response ==> ', response)
this.props.addNewImage(url,this.props.arrayname);
return response;
}).catch(error => {
console.log('[AWS S3] Error ==> ', error)
return error;
})
}
_handleImageChange(e){
let reader = new FileReader();
let file = e.target.files[0];
console.log(file,'file');
reader.onloadend = () => {
let uri=reader.result;
let fileType = /^data:image\/\w+;/.exec(reader.result)[0].replace(/^data:image/,"").replace("/","").replace(";","");
let fileName='img'+`${new Date().getTime()}`+'.'+fileType;
console.log("filename",fileName);
this.uploadToS3(uri,fileName,fileType,file);
}
reader.readAsDataURL(file);
}