一、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