AWS S3视频上传React Native



我使用AWS S3从Expo应用程序上传视频。我看到的大多数示例都是mp4文件。当我从Expo ImagePicker获得uri时,我收到一个mov文件。我很想知道如何正确地将视频文件从React Native应用程序上传到AWS S3

这是我上传视频到S3的代码:

const uploadVideoToS3 = async (file: any) => {
const date = new Date().toISOString();
const randomString = Math.random().toString(36).substring(2, 7);
const cleanFileName = file.toLowerCase().replace(/[^a-z0-9]/g, "-");
const newFileName = `${randomString}-${date}-${cleanFileName}`;
const newFile = new ReactNativeFile({
uri: file,
name: newFileName,
type: `${file.split(".").pop()}`,
});
AWS.config.update({
region: "eu-north-1",
credentials: new AWS.Credentials(AWS_S3_ACCESS_KEY, AWS_S3_SECRET_KEY),
});
let upload_params = {
Bucket: "bucket-name",
Key: file,
Body: file,
Acl: "public-read",
};
let upload = new AWS.S3.ManagedUpload({ params: upload_params });
let promise = upload.promise();
promise.then(
function (data) {
// ! Log only for testing
console.log("Successfully uploaded:", data);
// console.log(data);
// setVideoSource(data.Location);
},
function (err) {
console.log("Failed to upload", newFile, "with error:", err.message);
}
);
};

我也尝试使用CloudFront来提供视频,但由于我没有进一步尝试将视频上传到S3,这里的答案将是伟大的!

嗨,我也尝试了aws-sdk,但仍然无法上传,我尝试了后端预设的url,然后上传视频作品。

const uploadVideo = (token, data) => async dispatch => {
try {
dispatch({type: ASSET_LOADING});
const fileName = data.assets[0].fileName;
const fileType = 'mp4';
const fileSize = data.assets[0].fileSize / 1024;
const duration = data.assets[0].duration;
const fileUrl = data.assets[0].uri;
let success;
let url;
await api
.post(
'upload/presigned-url',
{
fileName,
fileType,
fileSize,
duration,
},
{
headers: {
token,
},
},
)
.then(response => {
success = true;
url = response.data.data.directUploadURL;
dispatch({
type: UPLOAD_VIDEO,
payload: response.data.data.videoId,
image: response.data.data.thumbnailUrl,
});
})
.catch(error => {
dispatch({type: UPLOADING_FAILED});
});
if (success) {
const formdata = new FormData();
formdata.append('file', {
uri: fileUrl,
name: fileName,
type: `application/${fileType}`,
});
const options = {
method: 'POST',
body: formdata,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
fetch(url, options)
.then(response => {
dispatch({type: UPLOADING_SUCCESS, payload: 'Uploading Success'});
})
.catch(error => {
dispatch({type: UPLOADING_FAILED, payload: 'Uploading failed'});
});
}
} catch (error) {
throw error;
}
};

相关内容

  • 没有找到相关文章

最新更新