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

该博客介绍了如何使用Python的Django框架结合JavaScript,通过表单实现文件上传功能。内容涉及前端JS处理、后端Django models.py和views.py的设置,特别强调了上传文件必须为txt格式,并在文件存在时进行替换处理。

这段代码适用于利用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())
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值