Skip to content

Instantly share code, notes, and snippets.

@iMerica
Created December 28, 2018 21:18
Show Gist options
  • Save iMerica/27d876bce830f67d851c37e242e3ab93 to your computer and use it in GitHub Desktop.
Save iMerica/27d876bce830f67d851c37e242e3ab93 to your computer and use it in GitHub Desktop.
Django/DRF File Uploading to S3
const notifyDjango = (url) => {
// Record the URL of the file you've uploaded along with any data
// that is relevent to you.
}
const uploadToS3 = (file, url) => {
// Upload the file here
// See https://git.io/fhIz5 as a great example of handling all S3 upload edge cases.
}
const getSignedUrl = (file) => {
const params = {
objectName: file.name,
contentType: file.type
};
client.get('/s3/signed-url/', { params })
.then(data => {
uploadToS3(file, data).then(i => {
// if success, record the new URL
notifyDjango(data)
})
})
.catch(error => {
console.error(error);
});
}
from botocore.exceptions import ParamValidationError
from django.http import JsonResponse
def get_signed_url(request, *args, **kwargs):
object_name = request.GET.get('objectName')
content_type = request.GET.get('contentType')
try:
url = conn.generate_presigned_url(
ClientMethod='put_object',
Params={
'Bucket': settings.S3_UPLOAD_BUCKET,
'Key': object_name,
'ContentType': content_type,
'ACL': 'public-read',
},
ExpiresIn=3600
)
return JsonResponse({'signedUrl': url})
except ParamValidationError:
return JsonResponse({'error': 'Invalid Input'}, status=400)
@Akohrr
Copy link

Akohrr commented Dec 28, 2018

Thank you very much. I'll definitely try this out next time I have to deal with file uploads in django.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment