-
-
Save ronaldlangeveld/4d68c365f4e71ff67a2c4c2f1dcd3689 to your computer and use it in GitHub Desktop.
Django Ajax File Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//HtML | |
<form> | |
{% csrf_token %} | |
<input type="file" name="pic" accept="image/*" id="image"> | |
<input type="submit" id="send"> | |
</form> | |
//JS | |
$('form').submit(function(e) { | |
e.preventDefault(); | |
var formData = new FormData($(this)); | |
console.log(formData); | |
formData.append('image', $('#image')[0].files[0]); | |
$.ajax({ | |
url: '/uploadimg', | |
type: 'POST', | |
data: formData, | |
cache: false, | |
contentType: false, | |
processData: false, | |
success: function(data) { | |
console.log(data.url) | |
var refresh = ''; | |
$('#featimg').val(refresh); | |
$('#featimg').val(data.url); | |
// ADDS The URL to an inputfield | |
}, | |
}); | |
}); | |
views.py | |
from django.conf import settings | |
from django.core.files.storage import FileSystemStorage | |
@login_required | |
def upload_image(request): | |
folder = settings.MEDIA_ROOT | |
if request.method == 'POST': | |
myfile = request.FILES['image'] | |
fs = FileSystemStorage(location=folder) | |
filename = fs.save(myfile.name, myfile) | |
file_url = fs.url(filename) | |
print(file_url) | |
print(filename) | |
return JsonResponse({"ok": "ok", "url": file_url}) | |
# sends file_url as json to frontend | |
else: | |
return JsonResponse({"fail": "fail"}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment