Django之三种文件上传
方式一:
通过form表单提交到后台
前端:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload/" method="post" enctype="multipart/form-data"> <input type="file" name="fafafa"> <input type="submit"> </form> </body> </html>
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提交
前端
<div> <input type="file" name="file" id="file_upload"> <input type="button" value="上传" onclick="FileUpload()"> </div>
JS:
<script src="/static/js/jquery-3.2.1.min.js"></script> <script> function FileUpload() { var form_data = new FormData(); var file_info =$( '#file_upload')[0].files[0]; form_data.append('file',file_info); //if(file_info==undefined)暂且不许要判断是否有附件 //alert('你没有选择任何文件'); //return false $.ajax({ url:'/upload_ajax/', type:'POST', data: form_data, processData: false, // tell jquery not to process the data contentType: false, // tell jquery not to set contentType success: function(callback) { console.log('ok') } }); }</script>
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标签提交:
httml
<h1>测试Imframe</h1> <input type="text" id="url"> <input type="button" value="点击" onclick="iframeChange()"> <iframe id="ifr" src=""></iframe> <hr/> <h1>基于iframe实现formt提交 </h1> <form action="/upload_Formdata.html" method="post" target="iframe_123" enctype="multipart/form-data"> <iframe id="iframe_1" name="iframe_123" src="" onload="loadIframe();"></iframe> <input type="text" name="user"> <input type="file" name="fafafa"> <input type="submit"> </form>
js:这里from标签的target和iframe的那么保持一致,form提交后会跳转到或者链接到iframe
<script src="/static/jquery-2.1.4.min.js"></script> <script> function iframeChange() { var url = $('#url').val(); $('#ifr').attr('src',url) } function loadIframe() {//iframe加载完后执行 console.log(1) //获取iframe内部的内容 var str_json = $('#iframe_1').contents().find('body').text() var obj = JSON.parse(str_json) if(obj.status){ var img = document.createElement('img'); img.src = "/" + obj.path; $('#imgs').append(img); } } </script>
Django 后端:
import json def upload_Formdata(request): if request.method=="GET": img_list=models.Img.objects.all() return render(request,'upload_Formdata.html',{"img_list":img_list}) elif request.method=="POST": obj=request.FILES.get('fafafa') file_path=os.path.join('static','upload',obj.name) f=open(file_path,'wb') for chunk in obj.chunks(): f.write(chunk) f.close() models.Img.objects.create(path=file_path) ret = {'status':True,'path':file_path,'text':123} return HttpResponse(json.dumps(ret))
以上是文件上传的三种方式,在Tornado种也可以使用。
扩展:
在前段提交的时候 可以存在 checkbox 标签, 在Django中对于这种标签在后台获取值时用:
request.POST.getlist('favor', None) checkbox
其它
request.POST.get('favor', None) checkbox
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提交
前段
<div> <input type="file" name="file" id="file_upload"> <input type="button" value="上传" onclick="FileUpload()"> </div>
JS:
<script src="/static/js/jquery-3.2.1.min.js"></script> <script> function FileUpload() { var form_data = new FormData(); var file_info =$( '#file_upload')[0].files[0]; form_data.append('file',file_info); //if(file_info==undefined)暂且不许要判断是否有附件 //alert('你没有选择任何文件'); //return false $.ajax({ url:'/upload_ajax/', type:'POST', data: form_data, processData: false, // tell jquery not to process the data contentType: false, // tell jquery not to set contentType success: function(callback) { console.log('ok') } }); }</script>
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标签提交
前段:
<div> <form id="my_form" name="form" action="/upload_iframe/" method="POST" enctype="multipart/form-data"> <input type="text" name="user"> <input type="password" name="password"> <input type="file" name="file"> <input type="button" value="upload" onclick="UploadFile()"> </form> <iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe> </div>
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')
参考学习:https://www.cnblogs.com/jishuweiwang/p/6140132.html
以上是文件上传的三种方式,在Tornado种也可以使用。
扩展:
在前段提交的时候 可以存在 checkbox 标签, 在Django中对于这种标签在后台获取值时用:
request.POST.getlist('favor', None) checkbox
其它
request.POST.get('favor', None) checkbox