Sam Munroe Sam Munroe - 1 year ago 203
Ajax Question

Upload file to S3 using Ajax and Boto3 for Django

I have a django project in which I would like to upload all images to S3. I have installed boto3 and am able to print out my buckets. Thus I know I have a definite connection. Now my next step is to push a file to S3 using ajax. Below is the current setup I have. Will this approach work? One problem I have stumbled upon is the fact that Chrome returns C:\fakepath\filename.

Django view:

def change_project_image(request):
image = request.POST['image']

data = open(image, 'rb')
s3.Bucket('bucket-name').put_object(Key='filename.jpg', Body=data)

return HttpResponse('temporary return')


$('#project-image-upload').on('change', function(){
var image = $(this).val();

$.post('/project/change-project-image/', {image:image} function(data){

}, 'json');


<label class="btn btn-default btn-file">
Browse <input id="project-image-upload" type="file">

Answer Source

So I took a different approach and was able to access the object in the view. I added the input to a form which posts to my desired view and then I handle the file like so:

def change_project_image(request):
    image = request.FILES['image']
    #now I need to pull the temporary path of image and pass it to boto

    data = open('path_to_file', 'rb')
    s3.Bucket('bucket_name').put_object(Key='filename.jpg', Body=data)

The problem I had was that I forgot to add enctype="multipart/form-data" in my form so request.FILES['image'] was empty.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download