一、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和实现抽屉实例的更多相关文章

  1. 第三百一十九节,Django框架,文件上传

    第三百一十九节,Django框架,文件上传 1.自定义上传[推荐] 请求对象.FILES.get()获取上传文件的对象上传对象.name获取上传文件名称上传对象.chunks()获取上传数据包,字节码 ...

  2. django设置并获取cookie/session,文件上传,ajax接收文件,post/get请求及跨域请求等的方法

    django设置并获取cookie/session,文件上传,ajax接收文件等的方法: views.py文件: from django.shortcuts import render,HttpRes ...

  3. ajax 文件上传,ajax

    ajax 文件上传,ajax 啥也不说了,直接上代码! <input type="file" id="file" name="myfile&qu ...

  4. maven工程 java 实现文件上传 SSM ajax异步请求上传

    java ssm框架实现文件上传 实现:单文件上传.多文件上传(单选和多选),并且用 ajax 异步刷新,在当前界面显示上传的文件 首先springmvc的配置文件要配置上传文件解析器: <!- ...

  5. 利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载

    利用struts2进行单个文件,批量文件上传,ajax异步上传以及下载 1.页面显示代码 <%@ page language="java" import="java ...

  6. Django中的文件上传和原生Ajax

    概述 Django中的上传有3种方案: form 表单常规上传,但点击提交后会自动刷新页面 Ajax 上传,不刷新页面,(分为原生ajax上传和jQuery上传),IE7以上不兼容 iframe 上传 ...

  7. django文件上传、图片验证码、抽屉数据库设计

    1.Django文件上传之Form方式 settings.py, ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'd ...

  8. django 快速实现文件上传

    前言 对于web开来说,用户登陆.注册.文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说就没办法一步一步的操作练习:对 ...

  9. Python Django缓存,信号,序列化,文件上传,Ajax登录和csrf_token验证

    本节内容 models操作 Django的缓存 请求方式 序列化 Form 配合Ajax实现登录认证 上传文件 Ajax  csrf_token验证方式 1 models操作 单表查询: curd(增 ...

随机推荐

  1. CSharp - Comparison between IComparer and IComparable

    /* Author: Jiangong SUN */ I've already written an article introducing the usage of comparer here. I ...

  2. PowerShell常用的.Net 、COM对象(New-Object、Assembly)、加载程序集

    #新建随机数对象实例:$Ran = New-Object System.Random$Ran.NextDouble() 有时候,要使用的实例的类保存在独立的库文件中,PowerShell默认未加载,会 ...

  3. JSP http头消息

    头 描述 Accept 指定MIME类型 Accept-Charset 编码,例如utf-8 Accept-Encoding 编码方式,例如使用gzip压缩 Accept-Language 语言,例如 ...

  4. VSS的运用小内容(针对于vs2008版本)(小的问题都是,仅供参考--只针对于菜鸟级的)

    自己开始接触vss 的时候有些小的习惯没有很好的养成,下面的有关VSS内容都是简单的迁入迁出的问题,(仅供参考) 1.文件的迁入迁出:(.txt..xlsx..doc) a:文件的覆盖问题: 对于文件 ...

  5. 文件IO 练习题

    3.1 当读/写磁盘文件时,本章中描述的函数是否具有缓冲机制?请说明原因. 3.1 所有的磁盘 I/O 都要经过内核的块缓冲区(也称为内核的缓冲区高速缓存),唯一例 外的是对原始磁盘设备的 I/O,但 ...

  6. ctkPlugin插件系统实现项目插件式开发

    插件式开发体会: 自开始写[大话QT]系列就开始接触渲染客户端的开发,说是开发不如更多的说是维护以及重构,在接手这块的东西之前自己还有点犹豫,因为之前我一直认为客户端嘛,没什么技术含量,总是想做比较有 ...

  7. 局域网内使用linux的ntp服务

    假设我们的饿局域网无法连接外网,但又需要同步时间,怎么办? 1. 已局域网内的一台机器作为基础,适用date修改其他机器的时间,date -s ...,很不方便,这里不介绍. 2. 适用ntp服务,自 ...

  8. 关于Android NDK

    把解压后的ndk放在自己想放的位置 环境变量:ndk根目录添加到PATH=$PATH:<ndk-root-path> 使用NDK:在自己工作目录(可以是随意位置)下创建<Test&g ...

  9. Genymotion无法启动Virtual Box

    Genymotion是非常快速的Android模拟器.这两天搞了一下Android Studio,想用Genymotion跑起一下,但死活都启动不了.很奇怪,明明几个月前还顺利启动的. Genymot ...

  10. JavaScript单例模式

    一.什么是单例 意思是指获取的对象只有一份. 二.最通用的单例 任何时刻获取SingLeton.instance都是同一个对象 var SingLeton={ instance:{ property: ...