我尝试使用“angular Js”发布FormData然后使用直接发布html到django api但是它会失败,任何人都试过它并知道它请告诉我你的答案它是我尝试的完整代码:
HTML:
$scope.getFileDetails = function (e) {
$scope.files = [];
$scope.$apply(function () {
var file = e.files[0];
filename = '';
if ('name' in file)
filename = file.name;
else
filename = file.fileName;
});
};
$scope.uploadFiles = function () {
//FILL FormData WITH FILE DETAILS.
// ADD LISTENERS.
var objXhr = new XMLHttpRequest();
objXhr.addEventListener("progress", updateProgress, false);
objXhr.addEventListener("load", transferComplete, false);
// SEND FILE DETAILS TO THE API.
objXhr.open('POST', endpoint + '/collaboratoradmin/test/upload_driver', true);
var fd = new FormData();
fd.append("filename", filename);
fd.append("csv_file", file);
objXhr.send(fd);
}
// UPDATE PROGRESS BAR.
function updateProgress(e) {
if (e.lengthComputable) {
document.getElementById('pro').setAttribute('value', e.loaded);
document.getElementById('pro').setAttribute('max', e.total);
}
}
// CONFIRMATION.
function transferComplete(e) {
alert("Files uploaded successfully.");
}
Angular Js:
@api_view(['POST'])
def upload_driver(request):
if request.POST and request.FILES:
csvfile = request.FILES['csv_file']
dialect = csv.Sniffer().sniff(codecs.EncodedFile(csvfile, "utf-8").read(1024))
csvfile.open()
reader = csv.reader(codecs.EncodedFile(csvfile, "utf-8"), delimiter=',', dialect=dialect)
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
print(list1)
Django api:
{{1}}