Proses upload data biasanya menggunakan FORM yang di submit dengan tipe POST, cara ini tentunya mudah untuk di lakukan karena tidak memerlukan proses pengiriman data melalaui Ajax.
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="filetest" id="filetest">
<input type="button" value="save" onclick="doUpload()">
</form>
function doUpload(){
filetest = $('#filetest')[0].files[0]
formData = new FormData();
formData.append('filetest', filetest);$.ajax({
url : "/xxx/upload-test",
type: "POST",
data: formData,
contentType : false,
processData : false,
headers: {
'X-CSRFToken': document.getElementsByName('csrfmiddlewaretoken')[0].value
},
success: function(data){
console.log(data.message);
}
});
}
import json
from from django.http import HttpResponse
def doUpload(request):
response = {}
if request.POST:
testfile = request.FILES.get('testfile')
#todo action .......
response = {
'message':'success'
}
return HttpResponse(json.dumps(response), content_type="application/json")