Skip to content

Instantly share code, notes, and snippets.

@DerevenetsArtyom
Last active January 2, 2024 15:39
Show Gist options
  • Save DerevenetsArtyom/cbb642f54d352b5a05def72d45f079fb to your computer and use it in GitHub Desktop.
Save DerevenetsArtyom/cbb642f54d352b5a05def72d45f079fb to your computer and use it in GitHub Desktop.
[Upload Images with AJAX] #django #ajax
# Ajax jQuery
function upload(event) {
event.preventDefault();
var data = new FormData($('#ajax').get(0));
console.log(data)
$.ajax({
url: '/image_load/', // same url 'action' in form
type: 'POST',
data: data,
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
alert('success');
}
});
return false;
}
# models.py
class Image(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(upload_to='attempt2/', null=True, blank=True)
# html
<form method="POST" action='.' id="ajax" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="name" id="inputName">
<input type="file" name="image" id="inputFile">
<button id="submit" type="submit">Add</button>
</form>
# views.py
def upload_image(request):
if request.method == 'POST':
if request.is_ajax():
name = request.POST.get('name')
image = request.FILES.get('image')
image_new = Image(name=name, image=image)
image_new.save()
return render(request, 'uploader.html')
# Ajax jQuery
function upload(event) {
event.preventDefault();
var data = new FormData($('#ajaxFormImg').get(0));
$.ajax({
url: '/image_load/',
type: 'POST',
data: data,
contentType: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
$('#ajaxFormImg')[0].reset();
alert('success');
}
});
return false;
}
$(function() {
$('#ajaxFormImg').submit(upload);
});
# models.py
class Image(models.Model):
image = models.ImageField(null=True, blank=True)
# html
<form id="ajaxFormImg">
{% csrf_token %}
<input type="file" name="image">
<button type="submit">Add</button>
</form>
# views.py
def directupload(request):
if request.method == 'POST':
if request.is_ajax():
file = request.FILES.get('image')
today_folder = datetime.now().strftime("%B%d_%Y")
# Set full path to today_folder where file will be saved
path_to_img = os.path.join(settings.MEDIA_ROOT, today_folder)
# Check if today_folder already exists
if not os.path.exists(path_to_img):
os.mkdir(path_to_img)
img_path = os.path.join(path_to_img, file.name)
# Start writing to the disk
with open(img_path, 'wb+') as destination:
if file.multiple_chunks: # size is over than 2.5 Mb
for chunk in file.chunks():
destination.write(chunk)
else:
destination.write(file.read())
return render(request, 'uploader.html')
# Ajax jQuery
function upload(event) {
event.preventDefault();
var image = $('#id_image')[0].files[0];
var data = new FormData();
data.append('image', image)
$.ajax({
url: '/image_load/',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
$('#ajaxFormImg')[0].reset();
alert('success');
}
});
return false;
}
$(function() {
$('#ajaxFormImg').submit(upload);
});
# forms.py
class ImageForm(forms.Form):
image = forms.ImageField(required=False)
# html
<form id="ajaxFormImg">
{% csrf_token %}
{{ form }}
<button type="submit">Add</button>
</form>
# views.py
def handle_uploaded_file(f):
today_folder = datetime.now().strftime("%B%d_%Y")
# Set full path to today_folder where file will be saved
path_to_img = os.path.join(settings.MEDIA_ROOT, today_folder)
# Check if today_folder already exists
if not os.path.exists(path_to_img):
os.mkdir(path_to_img)
img_path = os.path.join(path_to_img, f.name)
with open(img_path, 'wb+') as destination:
if f.multiple_chunks: # size is over than 2.5 Mb
for chunk in f.chunks():
destination.write(chunk)
else:
destination.write(f.read())
def imageform(request):
if request.method == 'POST':
if request.is_ajax():
form = ImageForm(request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['image'])
else:
form = ImageForm()
return render(request, 'uploader.html', {'form': form})
@ferlyso
Copy link

ferlyso commented Jan 22, 2022

Hello and thank you § for tutorial thank you !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment