var previous_logo = "";
')
// ------------------------------------------------ -----------------------------
function LoadLogotype () {
var card_logo = $ ("# card_logo"). val ();
if ((card_logo! = "") && (previous_logo! = card_logo)) {
previous_logo = card_logo;
$ ("# uploadphoto"). submit ();
}
}
// ------------------------------------------------ -----------------------------
$ (function () {
setInterval ("LoadLogotype ()", 1000);
});
...
form id = "uploadphoto" target = "upload_frame" enctype = "multipart / form-data" action = "/ upload_logo /" method = "post">
Logo: / form>
...
iframe id = "upload_frame" name = "upload_frame" style = "display: none">
...
The server load logo processing function saves the file in the user's folder. Also the downloaded file is checked according to the list allowed_files - protection against the user downloading unauthorized files.
As a result, the function gives the URL to the file.# ------------------------------------------------- -----------------------------
def upload_logo (request):
'Handles upload of logo images'
alloved_files = ('.jpg', '.jpeg', '.png', '.gif')
id = request.session ['our_id']
path = settings.MEDIA_ROOT + 'uploads /% s /'% id
if not os.path.isdir (path):
try:
os.makedirs (path)
except:
return "Error: couldn’t create directory to upload files!"
for image_file in request.FILES:
filename = request.FILES [image_file] ['filename']
name, ext = os.path.splitext (filename)
if ext not in alloved_files:
continue
if filename == '':
continue
content = request.FILES [image_file] ['content']
f = open (path + filename, 'wb')
try:
f.write (content)
finally:
f.close ()
content = {
"Image": "/ appmedia / uploads /% s /% s"% (id, filename),
}
return render_to_response ("done.html", content, context_instance = RequestContext (request))
The result of rendering the done.html template will fall into the invisible IFRAME “upload_frame” . The script finds the card_logotype element in the parent document and replaces the URL of the image with the one sent by the server.html>
head>
script language = "JavaScript" type = "text / javascript">
parent.document.getElementById ('card_logotype'). src = "{{image}}"
/ script>
/ head>
body>
/ body>
/ html>
As a result, the user sees a change in the logo on the selected picture. The whole process takes place without a full page refresh. Only the contents of the hidden frame and the logo image are changed.
You can see how it works here: http://bicards.pythondevside.com/
Source: https://habr.com/ru/post/22838/
All Articles