django uploads images for simple verification and automatic modification of image names

Keywords: Django Python

Links to the original text: https://www.jianshu.com/writer#/notebooks/28758830/notes/51826042/preview

django implements automatic name modification after uploading files (pictures) and various reminders when uploading pictures on pages:

1. First, add a folder in your project, such as system, add _init_ py and storage.py files under the folder, and add the following code in storage.py:

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
# -*- coding: UTF-8 -*-
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
class ImageStorage(FileSystemStorage):
from django.conf import settings

def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
# Initialization
super(ImageStorage, self).__init__(location, base_url)

# Rewrite_save method 
def _save(self, name, content):
import os, time, random
# File extension
ext = os.path.splitext(name)[1] #[0] is the file name
#The original name of the uploaded file
source_name = os.path.splitext(name)[0]
# File directory
d = os.path.dirname(name)
# Define file name, year, month, day, time, second random number, MD5 encryption, etc.
fn = time.strftime('%Y%m%d%H%M%S')
fn = fn + '_%d' % random.randint(0,100)
#Define file name, md5 encryption method
import hashlib
hash = hashlib.md5()
hash.update(source_name.encode('utf-8'))
fn1 = hash.hexdigest()
# Rewrite synthetic file names
name = os.path.join(d, fn + ext) #If the file name is changed to fn1 by md5
# Calling parent class methods
return super(ImageStorage, self)._save(name, content)

2. Add the following code to the models.py file:

'''
Nobody answered the question? Xiaobian created a Python learning exchange QQ group: 857662006 
Looking for like-minded small partners, mutual help, there are good video learning tutorials and PDF ebooks in the group!
'''
from system.storage import ImageStorage

img=models.ImageField(upload_to='img/%Y/%m/%d',storage=ImageStorage())


Storage results are: img/2018/3/29/2018010356_15.png or img/2018/3/29/eafd7b7873f94e1a7dc9e568991a5645.jpg

3,views

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
def uploadImg(request):
if request.method == 'POST':
if request.FILES.get('img'): #img is the name of the input tag in upload.html
new_img = models.Upload_img(
img = request.FILES.get('img'),
name = request.FILES.get('img').name
)
type_list = ['.jpg','.png','.gif','.webp']
#Judging the format of uploaded pictures
if os.path.splitext(new_img.name)[1].lower() in type_list:
new_img.save()
return render(request,'blog1/upload.html')

4,upload.html

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input id="uploadimg" type="file" name="img" />
<button type="submit" onclick="submit_successful()">upload</button>
<p id="tip"></p>
<script>

function submit_successful()
{
var x = document.getElementById('uploadimg');
if (x.value == ''){
alert('Failed to upload, please select the image to upload!')


}
else
{
var AllowExt=['.jpg','.gif','.png','.webp'];
<!-- Get the picture format:.jpg,.png -->
var FileExt=x.value.substr(x.value.lastIndexOf(".")).toLowerCase();
<!-- Determine whether a string is in an array -->
if (AllowExt.toString().indexOf(FileExt) > -1){

alert('Upload success!!!');

}
else
{
alert('Upload failed. Upload file format is:(.jpg,.png,.gif,.webp),The current format is:'+FileExt+'Please re-upload!');
}
}


}
</script>
</form>

Posted by tom_b on Fri, 11 Oct 2019 07:37:09 -0700