Reputation: 16029
I have a Django form with an fileupload. In the view I want to pass this file to another server with an urllib post request.
I tried to put this file in an ordinary post variable like this.
views.py on first server:
def loadfile(request):
server_url = "foo"
class UploadFileForm(forms.Form):
filename = forms.FileField()
context['fileform'] = UploadFileForm()
#after button is pressed
if request.method == 'POST':
upload_file(context, server_url, request.FILES['filename'])
return render_to_response("bar")
def upload_file(context, server_url, image_data):
#create a temp file to store image on sever
temp = tempfile.NamedTemporaryFile()
for chunk in image_data.chunks():
temp.write(chunk)
temp.flush()
#build filename
origfilename = str(image_data)
extention = origfilename[origfilename.rfind("."):]
filename = uuid.uuid4().hex + extention
#encode image so it can be send
with open(temp.name, "rb") as f:
data = f.read()
encoded_string = base64.urlsafe_b64encode(data)
url = "http://" + server_url + "/uploadimage?filename=" + filename
urllib2.urlopen(url, "img_data="+encoded_string)
temp.close()
This works if the downsteam server is also an django testserver, but with nginx/uwsgi I run into "bad gateway" errors. I think this is because the buffer size of uwsgi is to small. So a solution would be to make an proper multipart post request.
The question is: How to easily create a multipart urllib request given a django fileupload request?
Upvotes: 2
Views: 2329