一、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. shell脚本采用crontab定时备份数据库日志

    测试服务器上才用定时脚本备份一个数据库 并打包压缩成tar避免文件过大 脚本如下: 测试服务器的shell backup_mysql.sh #!/bin/bash BASE_PATH=/alidata ...

  2. MongoDB 复制集 (三) 内部数据同步

    一 数据同步        一个健康的secondary在运行时,会选择一个离自己最近的,数据比自己新的节点进行数据同步.选定节点后,它会从这个节点拉取oplog同步日志,具体流程是这样的:      ...

  3. MINA2.0原理

    转自:http://blog.csdn.net/liuzhenwen/article/details/5894279 客户端通信过程  1.通过SocketConnector同服务器端建立连接  2. ...

  4. 部分 CM11 系统 Android 平板执行植物大战僵尸 2 黑屏的解决的方法

    原文 http://forum.xda-developers.com/showthread.php?t=2755197 部分 CM11 系统的 Android 平板(比如三星 GT-P5110 )执行 ...

  5. C语言 小游戏之贪吃蛇

    还记得非常久曾经听群里人说做贪吃蛇什么的,那时候大一刚学了C语言,认为非常难,根本没什么思路. 前不久群里有些人又在谈论C语言贪吃蛇的事了,看着他们在做,我也打算做一个出来. 如今大三,经过了这一年半 ...

  6. Linux下搭建Oracle11g RAC(2)----配置DNS服务器,确认SCAN IP可以被解析

    从Oracle 11gR2开始,引入SCAN(Single Client Access Name) IP的概念,相当于在客户端和数据库之间增加一层虚拟的网络服务层,即是SCAN IP和SCAP IP  ...

  7. minicom移植到ARM开发平台

    minicom需要ncurses库的支持.arm-linux-gcc中并没有此库故需要交叉编译ncurses,否则出现很多头文件.库函数找不到. 软件环境: ncurses-6.0 下载网址:http ...

  8. Python学习入门教程,字符串函数扩充详解

    因有用户反映,在基础文章对字符串函数的讲解太过少,故写一篇文章详细讲解一下常用字符串函数.本文章是对:程序员带你十天快速入门Python,玩转电脑软件开发(三)中字符串函数的详解与扩充. 如果您想学习 ...

  9. node安装 教程 + git初步

    我的系统是win8.1   64位 这个是对应的安装包:http://files.cnblogs.com/files/zxyun/node-v0.12.5-x64.zip 安装中有不懂可以参考下面的两 ...

  10. javascript 中状态改变触发事件

    转 有限状态机:是一个非常有用的模型,可以模拟世界上大部分事物. 它有三个特征: * 状态总数(state)是有限的. * 任一时刻,只处在一种状态之中. * 某种条件下,会从一种状态转变(trans ...