Python+Django+Js并利用表单实现文件上传

这段代码适用于利用form表单进行文件的提交,并保证所提交的文件格式为txt。

判断文件是否存在,如果存在则删除旧文件保存新文件并执行A,如果不存在则执行B。

前端:

{% csrf_token %}

JS:

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())
    

 

你可能感兴趣的:(Python+Django+Js并利用表单实现文件上传)