Day21 Django之Form文件上传、原生Ajax和实现抽屉实例
一、Form文件上传
"""
Django settings for prev_chouti project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'r@f)w@0$sqv4i5uk!3g77dm=h^xuly4jlh44jrv4)2u=(ifi%l' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'prev_chouti.urls' TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
] WSGI_APPLICATION = 'prev_chouti.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
settings.py
"""prev_chouti URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', views.upload),
]
urls.py
from django.shortcuts import render
from django.core.files.uploadedfile import InMemoryUploadedFile
import os # Create your views here.
#Form上传文件实例
def upload(request):
if request.method == 'POST':
user = request.POST.get('user')
img = request.FILES.get('img')
f = open(os.path.join('static', img.name),'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
print(user, type(img))
print(user, img)
return render(request,'upload.html')
views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form上传文件实例</title>
</head>
<body>
<form method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" name="user" />
<input type="file" name="img" />
<input type="submit" />
</form>
</body>
</html>
upload.html
二、原生Ajax
1、发送GET请求
"""prev_chouti URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^upload/', views.upload),
url(r'^ajax/', views.ajax),
url(r'^xhr_ajax/', views.xhr_ajax),
]
urls.py
from django.shortcuts import render,HttpResponse
from django.core.files.uploadedfile import InMemoryUploadedFile
import os,time # Create your views here.
#Form上传文件实例
def upload(request):
if request.method == 'POST':
user = request.POST.get('user')
img = request.FILES.get('img')
f = open(os.path.join('static', img.name),'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
print(user, type(img))
print(user, img)
return render(request,'upload.html') def ajax(request):
ctime = time.time() return render(request, 'ajax.html', {'ctime':ctime}) def xhr_ajax(request):
print(request.GET)
return HttpResponse('OK')
views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生Ajax</title>
</head>
<body>
{{ ctime }}
<input type="button" value="XMLHttpRequest按钮" onclick="XhrAjax();" />
<script>
function XhrAjax() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
}
xhr.open('GET', '/xhr_ajax/?p=123');
xhr.send();
}
</script>
</body>
</html>
ajax.html
2、发送POST请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生Ajax</title>
</head>
<body>
{{ ctime }}
<input type="button" value="XMLHttpRequest按钮" onclick="XhrAjax();" />
<script>
function XhrAjax() {
var xhr = new XMLHttpRequest();
//支持IE5,6
//var xhr = new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
}
//xhr.open('GET', '/xhr_ajax/?p=123');
//xhr.send();
xhr.open('POST', '/xhr_ajax/');
//设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
xhr.send('k1=v1;k2=v2');
}
</script>
</body>
</html>
ajax.html
from django.shortcuts import render,HttpResponse
from django.core.files.uploadedfile import InMemoryUploadedFile
import os,time # Create your views here.
#Form上传文件实例
def upload(request):
if request.method == 'POST':
user = request.POST.get('user')
img = request.FILES.get('img')
f = open(os.path.join('static', img.name),'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
print(user, type(img))
print(user, img)
return render(request,'upload.html') def ajax(request):
ctime = time.time() return render(request, 'ajax.html', {'ctime':ctime}) def xhr_ajax(request):
print(request.GET)
print(request.POST)
return HttpResponse('OK')
views.py
3、发送form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生Ajax</title>
</head>
<body>
{{ ctime }}
<input type="button" value="XMLHttpRequest按钮" onclick="XhrAjax();" />
<script>
function XhrAjax() {
var xhr = new XMLHttpRequest();
//支持IE5,6
//var xhr = new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
}
//xhr.open('GET', '/xhr_ajax/?p=123');
//xhr.send();
xhr.open('POST', '/xhr_ajax/');
//设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
//xhr.send('k1=v1;k2=v2');
var form = new FormData();
form.append('user','wang');
form.append('pwd','222222');
xhr.send(form);
}
</script>
</body>
</html>
ajax.html
4、上传文件基于原生Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form上传文件实例</title>
</head>
<body>
<form method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" />
<input type="submit" />
</form>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile1();">XMLHttpRequest上传</a>
<script>
function uploadFile1() {
var form = new FormData();
form.append('user',document.getElementById('user').value);
var fileObj = document.getElementById('img').files[0];
form.append('img', fileObj);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
};
xhr.open('POST', '/upload/', true);
xhr.send(form);
}
</script> </body>
</html>
upload.html
#Form上传文件实例
def upload(request):
if request.method == 'POST':
user = request.POST.get('user')
img = request.FILES.get('img')
f = open(os.path.join('static', img.name),'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
# print(user, type(img))
# print(user, img)
return HttpResponse('OK')
return render(request,'upload.html')
views.py
5、上传文件基于jQuery Ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Ajax上传文件实例</title>
</head>
<body>
<form method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" />
<input type="submit" />
</form>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile1();">XMLHttpRequest上传</a>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile2();">jQuery Ajax上传</a>
<script src="/static/js/jquery-1.12.4.js"></script>
<script>
function uploadFile1() {
var form = new FormData();
form.append('user',document.getElementById('user').value);
var fileObj = document.getElementById('img').files[0];
form.append('img', fileObj);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
};
xhr.open('POST', '/upload/', true);
xhr.send(form);
}
function uploadFile2() {
/*
jQuery的对象与dom对象转换
dom对象
var i = document.getElementById('i1');
jQuery对象
var j = $('#i1');
$(i) dom-->jQuery
j[0] jQuery-->dom
document.getElementById('img').files[0];
$('#img')[0].files[0];
*/
var fileObj = $('#img')[0].files[0];
var form = new FormData();
form.append('img', fileObj);
form.append('user', 'wang'); $.ajax({
type:'POST',
url:'/upload/',
data:form, //{'k1':'v1'}--> send('k1=v1')
processData:false, //tell jQuery not to process the data
contentType:false, //tell jQuery not to set contentType
success:function (arg) {
console.log(arg);
}
})
}
</script> </body>
</html>
upload.html
6、上传文件基于iframe
from django.shortcuts import render,HttpResponse
from django.core.files.uploadedfile import InMemoryUploadedFile
import os,time,json # Create your views here.
#Form上传文件实例
def upload(request):
if request.method == 'POST':
ret = {'status':False, 'data':''}
try:
user = request.POST.get('user')
img = request.FILES.get('img')
file_path = os.path.join('static', img.name)
f = open(file_path,'wb')
for chunk in img.chunks():
f.write(chunk)
f.close()
ret['status'] = True
ret['data'] = file_path
# print(user, type(img))
# print(user, img)
except Exception as e:
ret['error'] = str(e)
return HttpResponse(json.dumps(ret))
return render(request,'upload.html') def ajax(request):
ctime = time.time()
return render(request, 'ajax.html', {'ctime':ctime}) def xhr_ajax(request):
print(request.GET)
print(request.POST)
return HttpResponse('OK')
views.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iFrame上传文件实例</title>
<style>
.img{
width:300px;
height:600px;
}
</style>
</head>
<body>
<iframe id="my_iframe" style="display: none" src="" name="my_iframe"></iframe>
<form id="fo" method="POST" action="/upload/" enctype="multipart/form-data">
<input type="text" id="user" name="user" />
<input type="file" id="img" name="img" onchange="uploadFile3();" />
<input type="submit" />
</form>
<div id="container"> </div>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile1();">XMLHttpRequest上传</a>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile2();">jQuery Ajax上传</a>
<a style="display: inline-block;background-color: aquamarine;cursor: pointer;" onclick="uploadFile3();">测试iFrame</a>
<script src="/static/js/jquery-1.12.4.js"></script>
<script>
function uploadFile1() {
var form = new FormData();
form.append('user',document.getElementById('user').value);
var fileObj = document.getElementById('img').files[0];
form.append('img', fileObj);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//只有服务器端返回数据时,处理请求
if(xhr.readyState == 4){
//服务器端响应的内容已经接受完毕
console.log(xhr.responseText);
}
};
xhr.open('POST', '/upload/', true);
xhr.send(form);
}
function uploadFile2() {
/*
jQuery的对象与dom对象转换
dom对象
var i = document.getElementById('i1');
jQuery对象
var j = $('#i1');
$(i) dom-->jQuery
j[0] jQuery-->dom
document.getElementById('img').files[0];
$('#img')[0].files[0];
*/
var fileObj = $('#img')[0].files[0];
var form = new FormData();
form.append('img', fileObj);
form.append('user', 'wang'); $.ajax({
type:'POST',
url:'/upload/',
data:form, //{'k1':'v1'}--> send('k1=v1')
processData:false, //tell jQuery not to process the data
contentType:false, //tell jQuery not to set contentType
success:function (arg) {
console.log(arg);
}
})
}
function uploadFile3() {
$('#container').find('img').remove();
document.getElementById('my_iframe').onload = callback;
document.getElementById('fo').target = 'my_iframe';
document.getElementById('fo').submit();
}
function callback() {
var text = $('#my_iframe').contents().find('body').text();
var json_data = JSON.parse(text);
console.log(json_data);
if(json_data.status){
//已经上传成功
//预览创建img标签,src属性指向静态文件路径
var tag = document.createElement('img');
tag.src = "/" + json_data.data;
tag.className = 'img';
$('#container').append(tag);
}else{
alert(json_data.error);
} }
</script> </body>
</html>
upload.html
Day21 Django之Form文件上传、原生Ajax和实现抽屉实例的更多相关文章
- 第三百一十九节,Django框架,文件上传
第三百一十九节,Django框架,文件上传 1.自定义上传[推荐] 请求对象.FILES.get()获取上传文件的对象上传对象.name获取上传文件名称上传对象.chunks()获取上传数据包,字节码 ...
- django设置并获取cookie/session,文件上传,ajax接收文件,post/get请求及跨域请求等的方法
django设置并获取cookie/session,文件上传,ajax接收文件等的方法: views.py文件: from django.shortcuts import render,HttpRes ...
- ajax 文件上传,ajax
ajax 文件上传,ajax 啥也不说了,直接上代码! <input type="file" id="file" name="myfile&qu ...
- maven工程 java 实现文件上传 SSM ajax异步请求上传
java ssm框架实现文件上传 实现:单文件上传.多文件上传(单选和多选),并且用 ajax 异步刷新,在当前界面显示上传的文件 首先springmvc的配置文件要配置上传文件解析器: <!- ...
- 利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载
利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载 1.页面显示代码 <%@ page language="java" import="java ...
- Django中的文件上传和原生Ajax
概述 Django中的上传有3种方案: form 表单常规上传,但点击提交后会自动刷新页面 Ajax 上传,不刷新页面,(分为原生ajax上传和jQuery上传),IE7以上不兼容 iframe 上传 ...
- django文件上传、图片验证码、抽屉数据库设计
1.Django文件上传之Form方式 settings.py, ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'd ...
- django 快速实现文件上传
前言 对于web开来说,用户登陆.注册.文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说就没办法一步一步的操作练习:对 ...
- Python Django缓存,信号,序列化,文件上传,Ajax登录和csrf_token验证
本节内容 models操作 Django的缓存 请求方式 序列化 Form 配合Ajax实现登录认证 上传文件 Ajax csrf_token验证方式 1 models操作 单表查询: curd(增 ...
随机推荐
- Git(一)环境搭建 + 常用命令
上周研究了一下 Git,简单的使用了一下,个人感觉相对 SVN 来说还是有一定学习成本的,这次记录一些自己的学习过程以及常用的命令. 在学习的过程中,同事推荐了一个前辈写的教程([传送门]:Git教程 ...
- 英文Ubantu系统安装中文输入法
以前都是安装的中文Ubantu,但是有时候用命令行的时候中文识别不好,会出现错误,所以这次安装了英文版,但是安装后发现输入法不好用,于是就要自己安装输入法. 安装环境为Ubantu13.04 1.卸载 ...
- c#判断输入textbox是否为数字
asp.net判断输入文字是否是数字 方案一:/**//// <summary> /// 名称:IsNumberic /// 功能:判断输入的是否是数字 /// 参数:string oTe ...
- android 判断应用程序是否已安装
1.判断是否安装/** check the app is installed*/private boolean isAppInstalled(Context context,String packag ...
- servlet和手动创建servlet,断点调试
1. 什么是Servlet Servlet是一种用Java语言编写的Web应用组件 Servlet主要用于动态网页输出,扩展了Web服务器的功能 Servlet由Servlet容器进行管理 2. ...
- springmvc使用@ResponseBody返回json乱码解决方法
1.springmvc 3.2以上的版本解决乱码的方法: 第一步:在配置中加入: <mvc:annotation-driven> <mvc:message-converters re ...
- 【php】中【event】之实现方式
这两天看了点事件机制,那么在php中,如何实现最简单的事件呢? 废话不多说,我们上代码. <?php class Event{ //事件名称 public $name; //存储hander p ...
- CSS相对定位、绝对定位
CSS定位属性:position. 定位的基本思想:定义元素框相对于其正常位置应该出现的位置,或者相对于父元素.另一个元素或浏览器窗口本身的位置. position属性值:static.relativ ...
- 记录Access数据库更新操作大坑一个
对于更新Access数据库的操作,必须保持参数数组与sql语句中参数顺序一致,如下: public bool Update(MyModel model) { StringBuilder strSql ...
- PHP 发邮件不换行
Content-Type:用于定义用户的浏览器或相关设备如何显示将要加载的数据,或者如何处理将要加载的数据 MIME:MIME类型就是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件 ...