0

I am trying to implement a function in Django to upload an image from a client (an iPhone app) to an Amazon S3 server. The iPhone app sends a HttpRequest (method PUT) with the content of the image in the HTTPBody. For instance, the client PUTs the image to the following URL: http://127.0.0.1:8000/uploadimage/sampleImage.png/

My function in Django looks like this to handle such a PUT request and save the file to S3:

def store_in_s3(filename, content):
    conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY) # gets access key and pass key from settings.py
    bucket = conn.create_bucket("somepicturebucket")
    k = Key(bucket)
    k.key = filename
    mime = mimetypes.guess_type(filename)[0]
    k.set_metadata("Content-Type", mime)
    k.set_contents_from_string(content)
    k.set_acl("public-read")

def upload_raw_data(request, name):
    if request.method == 'PUT':
        store_in_s3(name,request.raw_post_data)
        return HttpResponse('Upload of raw data to S3 successful')
    else:
        return HttpResponse('Upload not successful')

My problem is how to tell my function the name of the image. In my urls.py I have the following but it won't work:

url(r'^uploadrawdata/(\d+)/', upload_raw_data ),

Now as far as I'm aware, d+ stands for digits, so it's obviously of no use here when I pass the name of a file. However, I was wondering if this is the correct way in the first place. I read this post here and it suggests the following line of code which I don't understand at all:

file_name = path.split("/")[-1:][0]

Also, I have no clue what the rest of the code is all about. I'm a bit new to all of this, so any suggestions of how to simply upload an image would be very welcome. Thanks!

Community
  • 1
  • 1
n.evermind
  • 11,944
  • 19
  • 78
  • 122

1 Answers1

1

This question is not really about uploading, and the linked answer is irrelevant. If you want to accept a string rather than digits in the URL, in order to pass a filename, you can just use w instead of d in the regex.

Edit to clarify Sorry, didn't realise you were trying to pass a whole file+extension. You probably want this:

r'^uploadrawdata/(.+)/$'

so that it matches any character. You should probably read an introduction to regular expressions, though.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks Daniel. But why is the linked answer irrelevant? It's trying to do an upload via PUT as well? I just have the feeling that I'm doing something fundamentally wrong. Perhaps I shouldn't use PUT for my purposes, or perhaps I should have some of the code in the linked answer which I don't understand... – n.evermind Feb 10 '12 at 20:27
  • Also, I tried url(r'^uploadrawdata/(\w+)/', upload_raw_data ), -- but get the error message "The current URL, uploadrawdata/MD5-HASH-SOMETHING.png/, didn't match any of these." when trying to PUT to http://127.0.0.1:8000/uploadrawdata/MD5-HASH-SOMETHING.png/ – n.evermind Feb 10 '12 at 20:30