这段代码适用于利用form表单进行文件的提交,并保证所提交的文件格式为txt。
判断文件是否存在,如果存在则删除旧文件保存新文件并执行A,如果不存在则执行B。
前端:
<form action="{% url 'searchform' %} method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="uploadfile" accept="text/plain" onchange="fileChange(this);">
</form>
JS:
<script>
function fileChange(target){
var name = target.value;
var filename = name.substring(name.lastIndexOf(".")+1).toLLowerCase();
if( fileName != "txt"){
alert("Please upload .txt file");
target.value="";
return
}
}
</script>
models.py:
class UploadFile(models.Model):
uploadpath = models.FileField('file',upload_to="/home/")
views.py:
class UploadForm(forms.Form):
uploadfile = forms.FileField()
def upload():
if request.method == "POST":
uf = UploadForm(request.POST,request.FILES)
if uf.is_valid():
uploadfile = uf.cleaned_data['uploadfile']
name = uploadfile.name
path = '/home/'+name
exist = os.path.exists(path)
if exist == false:
file = UploadFile()
file.uploadpath = file
file.save()
//B
else:
noexists = "rm -f"+path
cmd = os.system(noexists)
file = UploadFile()
file.uploadpath - file
file.save()
//A
else:
uf = UploadForm()
return render(request,"xx.html",locals())