今天尝试了下用django实现文件的上传,参考了这篇博客:
一、通过form表单进行文件的上传下载
我们先来理清一下思路,整个流程就是通过form表单选择文件,点击提交按钮,通过action后面的链接路由到django的视图函数,接收数据,写入要存储的文件夹中
1.我们先设置要存储的路径,这里是在settings文件最后面配置了一个MEDIA_ROOT的路径,用来存放上传的文件,目录结构如图所示
MEDIA_ROOT = os.path.join(BASE_DIR,'static/media')
目录结构
路径下面没有波浪线就是正确的路径
2.创建视图处理文件上传,我这里加了个判断是否是excel文件,可以直接注释掉
from django.http import HttpResponse
from django.conf import settings # 导入django配置文件
import os
def fileManagerUpload(request):
'''文件上传'''
if request.method == 'POST':
try:
myFile = request.FILES.get("myfile", None)
print(myFile)
if not myFile:
return HttpResponse('没有要上传的文件')
if os.path.splitext(myFile.name)[1] != ".xlsx" :
# 如果上传的不是xlsx文件,返回错误信息
return HttpResponse("请上传指定格式文件")
destination = open(os.path.join(settings.MEDIA_ROOT, myFile.name), 'wb+')
for chunk in myFile.chunks():
destination.write(chunk)
destination.close()
return HttpResponse('成功!!')
except:
return HttpResponse('失败')
3.配置上传视图的路由,按照自己的情况创建
re_path('^fileManagerUpload/',ad_fileManager.fileManagerUpload,name='fileManagerUpload'),
这种方式路由需要导入re_path包
from django.urls import re_path
4.配置html模板,这里是fileManager.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form enctype="multipart/form-data" action="{% url 'fileManagerUpload' %}" method="post">
<input type="file" name="myfile" id="avatar_file"/>
<br/>
<input type="submit" value="upload">
</form>
</body>
</html>
5.配置模板的路由,按照自己的情况配置就好了
# 文件管理
re_path('^fileManager/',ad_views.fileManager,name='fileManager'),
6.我们启动项目测试一下
- html页面是这样的:
- 选中上传一个测试的excel文件
- 点击提交
- 可以看到media文件夹中多了一个test.xlsx文件
二、通过Jquery的ajax进行文件上传
1.在前面的基础上,我们只需要导入一个jQuery文件,修改一下模板文件即可。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<div>
<input type="file" name="myfile" id="file_upload">
<input type="button" value="上传" onclick="FileUpload()">
</div>
<script src="/static/lib/jquery/jquery.js"></script>
<script>
function FileUpload() {
var form_data = new FormData();
var file_info = $('#file_upload')[0].files[0];
form_data.append('myfile', file_info); //这里的myfile与视图中获取的request.FILES.get("myfile", None)要一致
$.ajax({
url: '{% url 'fileManagerUpload' %}',
type: 'POST',
data:form_data,
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
success: function (data) {
alert(data);
}
})
}
</script>
</body>
</html>
2.我们测试一下