Last active
October 25, 2022 19:53
-
-
Save xpsdeset/fc2c8789247f14d6cb4fec44323883b4 to your computer and use it in GitHub Desktop.
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
<input id="fileupload" type="file" name="fileupload" /> | |
<button id="upload-button" onclick="uploadFileHandler()"> Upload </button> | |
<script> | |
function uploadFileHandler() { | |
let formData = new FormData(); | |
const file = document.getElementById('fileupload').files[0]; | |
uploadFile(file) | |
} | |
const uploadFile = async (file) => { | |
let uploadedUrl | |
if( file && typeof file != 'string' ){ | |
let { name, type } = file | |
// path to your api server where getting signed url is hosted | |
let uploadURl = (await axios.post('host/get-signed-url', { name, type })).data | |
return new Promise((resolve) => { | |
const formData = new FormData() | |
formData.append("file", file) | |
return axios | |
.put(uploadURl, file, { | |
headers: { | |
"X-Requested-With": "XMLHttpRequest", | |
"Content-Type": type, | |
}, | |
}) | |
.then((response) => { | |
uploadedUrl= uploadURl.split("?")[0] | |
resolve(uploadedUrl) | |
return uploadedUrl | |
}) | |
.catch((error) => { | |
throw "Error uploading images" | |
}) | |
}) | |
}else{ | |
return uploadedUrl = file | |
} | |
} | |
</script> |
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
var AWS = require("aws-sdk") | |
var Bucket = "" | |
var region = "" | |
var path = "uploads/" | |
var apiVersion = "2006-03-01" | |
// if needed | |
AWS.config.update({ | |
region, | |
}) | |
var s3 = new AWS.S3({ | |
apiVersion, | |
params: { Bucket }, | |
}) | |
router.get('/get-signed-url',(req,res)=>{ | |
// eg: req.body.filename => "a.jpg" | |
var params = { Bucket, Key: req.body.filename } | |
s3.getSignedUrl("putObject", params, function (err, url) { | |
res.json({url}) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment