I'm currently trying to post a file to a service endpoint, written in django.
I can find a bunch of examples like this (exert from here):
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponseRedirect('/success/url/')
........
but how do I make a request using either the test client or urllib which can pass files to the server when it isn't coming from an HTML form? I'm currently trying to urlencode the file contents into a json string and then pass that along; but that is proving to be cumbersome.
IN ADDITION TO ANSWER BELOW:
- Don't forget to make your service csrf exempt
- Don't set the content type or set it explicitly to multipart.
- Consult this for info on how to handle incoming files in your view.