在前面的https://mp.csdn.net/postedit/80586507,https://mp.csdn.net/postedit/80586917这两个博客中初步的了解样式以及如何往后台传输文件,这一篇就简单的写一下后台的获取,用的后台python+django,有兴趣的可以学一下。
在上一节中upload 上传文件,用的是formdata,通过ajax传递,当然这个表单提交也是可以的,在我们传递了文件后,那么后台怎么获取呢?大致的代码如下:
#python3.6 后台代码
def getFile(request):
file = request.Files.get("file") #所有form表单提交的文件
hh = request.POST.get("hh") #form表单里面的其他内容
flagCount = file.name.count(".") #file.name指文件的名 file.name.count(".") 计算.号出现的次数
endFix = file.name.split(".",flagCount)[flagCount] #获取文件的后缀
save_path = "D:\\hhh" #文件存放的路径
if os.path.exists(all_path) == False: #没有该文件夹时生成该文件夹
os.mkdir(all_path)
all_path = save_path + file.name
file_iterator(all_path,file) #生成文件的函数
return Httpresponse("ok")
def file_iterator(all_path,file):
with open(all_path,"wb") as f:
for chunk in file.chunks(chunk_size=1024):
if chunk:
f.write(chunk)
else:
break
当然getFile函数还可以做很多操作,比如说某用户上传了一个乱七八糟的文件,其实这个对于系统来说是极其不好的,那么我们就要过滤掉,当然有人说前台传文件的时候就应该限制不让它传递了,这也可以。在file的input可以这么写。
<input type="file" class="form-control" accept=".xlsx,.xls,.doc,.docx" id="projectfile" />
当然accept只是限制了打开框展示的文件是以.xlsx,.xls,.doc,.docx这种后缀结尾的文件,并没有起到多大的限制文件的作用。
然后js处理是这样子的
$('input[id=projectfile]').change(function () {
var isExists == false;
var filename = ($(this).val().replace(/^.+?\\([^\\]+?)(\.[^\.\\]*?)?$/gi, "$1"));
var endname = ($(this).val().replace(/.+\./, "").toLowerCase());
var index_arr = ["xlsx","xls","doc","docx"];
for (var i in array) {
if (endname == index_arr[i].toLowerCase()) {
isExists = true;
return true;
}
}
if (isExists == false) {
alert("上传图片类型不正确!");
return false;
}
});
通过后台也一样
在后台的代码里添加这么一行代码:
def getFile(request):
file = request.Files.get("file") #所有form表单提交的文件
hh = request.POST.get("hh") #form表单里面的其他内容
flagCount = file.name.count(".") #file.name指文件的名 file.name.count(".") 计算.号出现的次数
endFix = file.name.split(".",flagCount)[flagCount] #获取文件的后缀
if endFix not in ["xlsx","xls","doc","docx"]:
return HttpResponse("文件类型错误")
save_path = "D:\\hhh" #文件存放的路径
if os.path.exists(all_path) == False: #没有该文件夹时生成该文件夹
os.mkdir(all_path)
all_path = save_path + file.name
file_iterator(all_path,file) #生成文件的函数
return HttpResponse("ok")
然后文件的后台代码就到这里了。