-
-
Save renatoalencar/04d850be19891fd4bf16016d61bbc6a2 to your computer and use it in GitHub Desktop.
Upload progress Node.js + Axios
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AWS_ACCESS_KEYID= | |
AWS_SECRET_KEY= | |
BUCKET= |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express') | |
const fs = require('fs') | |
const path = require('path') | |
const multiparty = require('multiparty') | |
const AWS = require('aws-sdk') | |
require('dotenv').config() | |
const s3 = new AWS.S3({ | |
accessKeyId: process.env.AWS_ACCESS_KEYID, | |
secretAccessKey: process.env.AWS_SECRET_KEY | |
}) | |
const FOLDER = 'artifacts' | |
async function upload (req, res) { | |
const form = new multiparty.Form() | |
form.on('part', async (part) => { | |
if (part.name !== 'artifact' || part.filename === undefined) return | |
const result = await s3.upload({ | |
Bucket: process.env.BUCKET, | |
Key: `${FOLDER}/${part.filename}`, | |
Body: part, | |
ContentLength: part.byteCount | |
}).promise() | |
res.json(result) | |
}) | |
form.parse(req) | |
} | |
function index (req, res) { | |
res.sendFile(path.resolve('index.html')) | |
} | |
express() | |
.post('/upload', upload) | |
.get('/', index) | |
.listen(3000) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Upload</title> | |
</head> | |
<body> | |
<input id="artifact" type="file" name="artifact" /> | |
<button id="send" type="button">Send</button> | |
<i id="status"></i> | |
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> | |
<script> | |
function updateStatus(status) { | |
document | |
.getElementById('status') | |
.innerText = `${status}%` | |
} | |
async function upload (e) { | |
const form = new FormData() | |
const artifact = document | |
.getElementById('artifact') | |
form.append('artifact', artifact.files[0]) | |
const response = await axios.post('/upload', form, { | |
onUploadProgress(event) { | |
const percent = (event.loaded * 100 / event.total).toFixed(2) | |
updateStatus(percent) | |
} | |
}) | |
console.log(response) | |
} | |
document | |
.getElementById('send') | |
.addEventListener('click', upload) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment