Reputation: 13218
I am making an Ajax POST Request and it does not get recognized in my view.
Code in views.py:
@csrf_exempt
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#handle_uploaded_file(request.FILES['file'])
f = request.FILES['file']
global globalVarForToTrackUpload
global globalFileSizeVariable
globalFileSizeVariable = f.size
filename = "/static/Data/" + f.name
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
globalVarForToTrackUpload += len(chunk)
destination.close()
#return render_to_response('uploadsuccess.html')
allValues = str(globalVarForToTrackUpload) + " : " + str(globalFileSizeVariable)
return HttpResponse(allValues)
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
My middleware settings are :
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
My javascript function is:
function submitForm()
{
//document.forms["myForm"].submit();
xhrPost = getXhrObject();
var arrFiles = document.getElementById('id_file');
var fileToUpload = arrFiles.files[0];
xhrPost.onreadystatechange = function() {
if(xhrPost.readyState == 4 && xhrPost.status == 200)
document.getElementById("upload-progress-bar").innerHTML = xhrPost.responseText;
else
document.getElementById("upload-progress-bar").innerHTML = "processing upload...";
}
xhrPost.open("POST","/upload.psp/",true);
var boundary = "AJAX--------------" + (new Date).getTime();
var contentType = "multipart/form-data; boundary=" + boundary;
xhrPost.setRequestHeader("Content-Type", contentType);
xhrPost.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
xhrPost.send(fileToUpload);
return false;
}
Can anybody tell me what I am missing? Why is the request not getting recoginzed as "POST" in my "upload" function inside views.py?
Thanks in advance.
Upvotes: 0
Views: 881
Reputation: 101
Use request.raw_post_data in your view. Somehow like this:
if request.is_ajax():
source = request.raw_post_data
#Save or/and modify your file
else:
#As usual
By the way, i do not know how to get file by chunks. Maybe someone knows.
Upvotes: 2