一、Form表單方式送出:
form表單送出檔案或者圖像時需要對form中的屬性進行如下設定:
1、method="post" //送出方式 post
2、enctype="multipart/form-data" //不對字元編碼。在使用包含檔案上傳控件的表單時,必須使用該值。
3、action="/code/" //送出給哪個url
code.html檔案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>代碼統計</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/code/">
{% csrf_token %}
<input type="file" name="file" value="上傳檔案">
<button type="submit" id="btn">送出</button>
</form>
</body>
</html>
url
url(r'code/$',views.code)
views.py
def code(request):
if request.method == "POST":
filename = request.FILES['file'].name
with open(filename, 'wb') as f:
for chunk in request.FILES['file'].chunks():
f.write(chunk)
return HttpResponse('上傳成功')
return render(request, 'code.html')
二、ajax方式送出檔案:
直接上代碼吧,代碼有注釋
code.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>代碼統計</title>
</head>
<body>
<form>
{% csrf_token %}
<input type="file" name="file" value="上傳檔案">
<button type="button" id="btn">送出</button>
</form>
<script src="/static/js/jquery-3.3.1.js"></script>
<script>
$("#btn").click(function () {
//建立一個FormData對象用來存儲資料
var file_obj = new FormData;
//通過jquery的的屬性操作找到上傳的檔案,
// 注意files方法是js對象的特有的方法,是以需要将jquery對象索引轉化成js對象調用此方法
file_obj.append('file', $("input[type='file']")[0].files[0]);
//jquery的屬性操作擷取csrftoken值來防禦CSRF攻擊
file_obj.append('csrfmiddlewaretoken', $('[name=csrfmiddlewaretoken]').val());
$.ajax({
url: '/code/',
type: 'post',
processData: false,//不讓jQuery處理我的file_obj
contentType: false,//不讓jQuery設定請求的内容類型
data: file_obj,
//成功回調函數
success: function (res) {
console.log(res.msg)
}
})
})
</script>
</body>
</html>
url:
url(r'code/$',views.code)
views.py:
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
def code(request):
res={'code':0}
if request.method == "POST":
file_obj = request.FILES['file']
filename = file_obj.name
with open(filename, 'wb') as f:
for chunk in file_obj.chunks():
f.write(chunk)
res['msg'] = '上傳成功'
return JsonResponse(res)
return render(request, 'code.html')