Document
上传文件:
文件上传进度:
文件上传状态:
后端代码
def upload_files(request):
if request.method == 'POST':
try:
get_file = request.FILES.get('file')
if get_file is not None:
# print type(get_file) # # print get_file.read()
for con in get_file.readlines():
line = con.strip("\n")
if line.startswith("#"):
pass
else:
print line
return HttpResponse("success!")
else:
print u"文件对象是None"
return HttpResponse("false!")
except Exception, e:
print e
return HttpResponse("false!")
后面的几种方法没试:
方式一:
通过form表单提交到后台
前端:
Title
Django 后端:
def upload(request):
if request.method == 'POST':# 获取对象
obj = request.FILES.get('fafafa')
import os
# 上传文件的文件名
print(obj.name) f = open(os.path.join(BASE_DIR, 'static', 'pic', obj.name), 'wb')
for chunk in obj.chunks():
f.write(chunk)
f.close()
return HttpResponse('OK')
return render(request, 'upload/upload.html')
方式二:
通过ajax提交
前端
JS:
Django 后端:
def upload_ajax(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
print('11111')
return HttpResponse('OK')
注意:
前台发送ajax请求时:
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
必须设置
方式三:
通过iframe标签提交
前端:
JS:
function UploadFile() {
document.getElementById('my_iframe').onload = Testt;
document.getElementById('my_form').target = 'my_iframe';
document.getElementById('my_form').submit();
}
function Testt(ths){
var t = $("#my_iframe").contents().find("body").text();
console.log(t);
}
Django 后端:
def upload_iframe(request):
if request.method == 'POST':
print(request.POST.get('user', None))
print(request.POST.get('password', None))
file_obj = request.FILES.get('file')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
print('11111')
return HttpResponse('OK')
以上是文件上传的三种方式,在Tornado种也可以使用。
扩展:
在前段提交的时候 可以存在 checkbox 标签, 在Django中对于这种标签在后台获取值时用:
request.POST.getlist('favor', None) checkbox
其它
request.POST.get('favor', None) checkbox