代码如下:
const updatePhotoHandler = () => {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true,
}).then((image) => {
console.log('image', image);
setImage(image);
setPhoto(image.path);
});
image != '' && uploadImageToAWS(image);
};
const uploadImageToAWS = async (imageFile) => {
console.log('upload image to aws', imageFile);
var files = [imageFile];
console.log('upload file to aws', files);
var fileKey = 'some key';
uploadMultipleFiles(files, fileKey, uploadSuccess, uploadError);
};
const uploadMultipleFiles = (files, fileKey, cbSuccess, cbError) => {
var baseScope = {};
baseScope.numberOfUploads = files.length;
baseScope.uploadInfo = {};
baseScope.afterUploadFileCB = cbSuccess;
for (var i in files) {
var file = files[i];
baseScope.uploadInfo[file.path] = '';
uploadFile(file, fileKey, handleFileUploadSuccess, cbError, baseScope);
}
};
const uploadFile = (file, fileKey, cbSuccess, cbError, baseScope) => {
console.log('fileeee', file);
console.log('upload filekey', fileKey);
var mimetype = getMimeType(file.mime);
console.log('mime', mimetype);
// console.log("Blob data ",encryptedDataBlob)
let awsUploadLink = `${ROOT}/get-aws-upload-signature`;
console.log('aws',awsUploadLink)
let url = new URL(awsUploadLink);
let urlParams = {mimetype: mimetype};
Object.keys(urlParams).forEach((key) =>
url.searchParams.append(key, urlParams[key]),
);
fetch(url, {
method: 'POST',
credentials: 'include',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
.then((response) => response.json())
.then((response) =>
awsSignaturePolicyResponse(
response,
file,
fileKey,
mimetype,
cbSuccess,
cbError,
baseScope,
).catch((error) => {
console.error('Error while uploading to s3 ', error);
if (cbError) {
cbError('Error while uploading file ' + error);
}
}),
);
};
const awsSignaturePolicyResponse = async (
response,
file,
fileKey,
mimetype,
cbSuccess,
cbError,
baseScope,
) => {
if (response['code'] === 200) {
console.log('file',file)
let awsSignature = response['content']['s'];
let awsPolicy = response['content']['p'];
let dataBlob = new Blob([file], {type: mimetype});
var uploadPath = fileKey + generateUniqueFileName(file.path);
let formData = new FormData();
formData.append('policy', awsPolicy);
formData.append('signature', awsSignature);
formData.append('acl', 'public-read');
formData.append('AWSAccessKeyId', AWS_ACCESS_KEY);
formData.append('key', uploadPath);
// console.log("Key is ",uploadPath);
formData.append('Content-Type', mimetype);
formData.append('file', dataBlob);
let awsFileUrl = awsS3URL + '/' + uploadPath;
let uploadUrl = awsS3URL;
fetch(uploadUrl, {
method: 'POST',
credentials: 'include',
body: formData,
})
.then((response) => cbSuccess(file.name, awsFileUrl, baseScope))
.catch((error) => {
console.error('Error while uploading to s3 ', error);
if (cbError) {
cbError('Error while uploading file ' + error);
}
});
}
};
现在,每当我尝试将 file.path 上传到 s3 时,我都会收到网络请求失败。 我从图像选择器接收到的图像对象如下
卡住了很久,如果有人能告诉我哪里出错了,如果有人能帮助我,我将非常感激。 任何线索将不胜感激。