0
Ich verwende den Federeditor, um ein Bild hochzuladen, und die AJAX-Funktion wird verwendet, um das Bild an views.py zu senden.Django gibt 400 Schlechter Anforderungsfehler beim Bildupload mit Ajax
Dies ist die Python-Funktion zum Hochladen des Bildes.
views.py
def upload_image(request):
if request.method == 'POST':
handle_uploaded_file(request.FILES.get('file'))
return HttpResponse("Successful")
return HttpResponse("Failed")
def handle_uploaded_file(file):
with open('upload/', 'wb+') as destination:
for chunk in file.chunk():
destination.write(chunk)
Dies ist die Ajax-Anfrage:
function upload(file, callback) {
console.log('called');
var formData = new FormData();
formData.append('file', file);
$.ajax({
url : '{% url 'dashboard:upload_image' %} ',
type : 'POST',
data : formData,
contentType: 'multipart/form-data',
headers: { "X-CSRFToken": $.cookie("csrftoken") },
processData: false,
success: function(data) {
console.log('success');
callback(data.url)
}
});
}
Funktion Aufruf upload():
function(value) {
let fileInput = this.container.querySelector('input.ql-image[type=file]');
if (fileInput == null) {
fileInput = document.createElement('input');
fileInput.setAttribute('type', 'file');
fileInput.setAttribute('accept', 'image/*');
fileInput.classList.add('ql-image');
fileInput.addEventListener('change',() => {
if (fileInput.files != null) {
upload();
}
});
this.container.appendChild(fileInput);
}
fileInput.click();
}
}
könnten Sie die Ajax-Anfrage für das Hochladen von Bildern anzeigen? – zaidfazil
hinzugefügt, dass. @FazilZaid – Sanjana