<form class="form-group" method="post" action="/upload/" enctype="multipart/form-data">
<!-- enctype="multipart/form-data" 上传文件时必须添加 -->
{% csrf_token %}
<label for="">文件上传</label>
<input type="file" class="form-control-file" name="file" id="file" placeholder="请选择文件" aria-describedby="fileHelpId">
<!-- <input type="button" value="提交" id='submit'> -->
<input type="submit" value="提交">
<small id="fileHelpId" class="form-text text-muted"></small>
</form>
Ajax形式的文件上传
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="form-group">
{% csrf_token %}
<label for="">文件上传</label>
<input type="file" class="form-control-file" name="file" id="file" placeholder="请选择文件" aria-describedby="fileHelpId">
<input type="button" value="提交" id='submit'>
<small id="fileHelpId" class="form-text text-muted"></small>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
$('#submit').click(function(){
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
formData.append('csrfmiddlewaretoken', $("[name='csrfmiddlewaretoken']").val());
$.ajax({
url: '/upload/',
type: 'post',
// 上传文件时,这两个参数时必须的。
processData: false,
contentType: false,
data: formData,
success: function(rsp){
console.log(rsp);
}
});
});
</script>
</body>
</html>
服务端代码
def upload(request):
if request.method == 'POST':
print(request.FILES)
file = request.FILES.get('file')
file_path = os.path.join(settings.BASE_DIR, 'media', 'img', file.name)
with open(file_path, 'wb') as f:
for i in file:
f.write(i)
return JsonResponse({'code': 0, 'msg': '上传成功'})
return render(request, 'upload.html')