在经过上面的简单的小博客讲解后,今天就把前端和后端的代码粗略的弄一下。大致的代码如下:
{# 上传文件的时候必须要在form标签中添加属性 enctype="multipart/form-data" #}
<form method="POST" enctype="multipart/form-data" id="upload" >
<div class="col-lg-12">
<div class="col-lg-8">
<input type="file" name="img" id="img" class="btn btn-default"/>
<input type="text" name="companyF" id="companyF" value="{{ company_name }}" style="display: none;"/>
<input type="text" name="coverFile" id="coverFile" value="False" style="display: none;"/>
</div>
<div class="col-lg-4" style="text-align: center;">
<input type="button" class="btn btn-default" value="上传附件" onclick="transferBtn(this)" />
</div>
<div class="col-lg-4" style="text-align: center;">
<input type="button" class="btn btn-default" value="下载文件" onclick="downloadFiles()" />
</div>
</div>
</form>
//上传文件按钮
function transferBtn(cur){
var form = document.getElementById('upload'),
formData = new FormData(form);
$.ajax({
url:"{% url 'upload' %} ",
type:"post",
data:formData,
processData:false,
contentType:false,
success:function(data){
if(data == 'ok'){
layer.msg("上传成功!");
}
if(data == 'exists'){
//询问框
layer.confirm('已有该文件,是否覆盖?', {
btn: ['确定', '取消'],
}, //按钮
function () {
coverFile();
},
function () {
layer.msg('取消操作成功');
});
}
}
})
}
//覆盖文件的操作
function coverFile() {
var form = document.getElementById('upload');
$("#coverFile").val('True');
formData = new FormData(form);
$.ajax({
url:"{% url 'upload' %} ",
type:"post",
data:formData,
processData:false,
contentType:false,
success:function(data){
layer.msg('覆盖文件成功');
}
})
}
def upload(request):
if request.method == "POST":
company = request.POST.get("companyF")
file = request.FILES.get('img') # 所有提交的文件
coverFile = request.POST.get("coverFile")
file_name = file.name
path = tools.DOC_BASE_DIR + request.user.username + '/' + company + '/'
all_path = path + file_name
if os.path.exists(path) is False:
os.makedirs(path)
if os.path.exists(all_path) and coverFile == 'False':
return HttpResponse('exists')
with open(all_path, 'wb') as f:
for chunk in file.chunks():
f.write(chunk)
return HttpResponse("ok")
# return render(request, 'report_template.html')
def fileExistsOrNot(request):
company_name = request.POST.get("company_name")
file_name = request.POST.get("file_name")
path = tools.DOC_BASE_DIR + request.user.username + '/' + company_name + '/' + file_name
if os.path.exists(path):
return HttpResponse("文件名已存在")
else:
return HttpResponse("OK")