Skip to content

Instantly share code, notes, and snippets.

@it-one-mm
Created August 21, 2020 06:07
Show Gist options
  • Save it-one-mm/a60f7100d70b556b1cc22d23e36e09bc to your computer and use it in GitHub Desktop.
Save it-one-mm/a60f7100d70b556b1cc22d23e36e09bc to your computer and use it in GitHub Desktop.
File Upload using Ant with s3
import React, { useState } from 'react';
import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { generateDateForFileName } from '../utils/helpers';
const nodeServerEndpoint = 'http://localhost:4000/api/v1/aws/sign-s3';
const phpServerEndpoint = 'http://localhost:9000/api/v1/signed-url-put-object';
const UploadAnt = () => {
const [key, setKey] = useState<string>('');
const [loading, setLoading] = useState<boolean>(false);
return (
<div>
<Upload
disabled={loading}
accept="video/mp4"
customRequest={({ file, onError, onSuccess, onProgress }) => {
const fileType = file.type;
const fileName = file.name;
console.log('Preparing the upload');
console.log('fileType', fileType);
const key = `videos/${generateDateForFileName()}_${fileName}`;
console.log('key', key);
setKey(key);
setLoading(true);
axios
.post(`${phpServerEndpoint}`, {
key,
fileType,
})
.then((response) => {
var returnData = response.data;
var signedRequest = returnData.signedRequest;
console.log('Recieved a signed request ' + signedRequest);
// Put the fileType in the headers for the upload
var options = {
onUploadProgress: (event: ProgressEvent) => {
const { loaded, total } = event;
onProgress(
{
percent: Math.round((loaded / total) * 100),
},
file
);
},
headers: {
'Content-Type': fileType,
},
};
var t0 = performance.now();
axios
.put(signedRequest, file, options)
.then((result) => {
var t1 = performance.now();
console.log('Response from s3');
console.log(
'Call to doSomething took ' + (t1 - t0) + ' milliseconds.'
);
setLoading(false);
onSuccess(result, file);
message.success('Successfully Upload!');
})
.catch((error) => {
onError(error);
alert('ERROR ' + JSON.stringify(error));
});
})
.catch((error) => {
alert(JSON.stringify(error));
});
}}
>
<Button loading={loading}>
<UploadOutlined /> Click to Upload
</Button>
</Upload>
</div>
);
};
export default UploadAnt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment