Django 檔案上傳到後臺的三種方式
阿新 • • 發佈:2019-01-07
方式一:
通過form表單提交到後臺
前段:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{% url 'clashphone:Upload' %}" method="post" enctype="multipart/form-data"> <input type="file"name="fafafa"> <input type="submit"> {% csrf_token %} </form> </body> </html>
Django 後端:
class Upload(View): def get(self, request): return render(request, 'clashphone/test.html', { 'mould': os.path.join(BASE_DIR, 'media', 'commen'), 'MEDIA_URL': MEDIA_URL} ) def post(self, request): obj = request.FILES.get('fafafa', '1') print(obj.name) f = open(os.path.join(BASE_DIR, 'media', 'image', obj.name), 'wb') for chunk in obj.chunks(): f.write(chunk) f.close() # return render(request, 'clashphone/test.html')return HttpResponse('OK')
方式二:
通過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')
以上是檔案上傳的三種方式,在Tornado種也可以使用。
擴充套件:
在前段提交的時候 可以存在 checkbox 標籤, 在Django中對於這種標籤在後臺獲取值時用:
request.POST.getlist('favor', None) checkbox
其它
request.POST.get('favor', None) checkbox