1. 程式人生 > >Python+Django+Js並利用表單實現檔案上傳

Python+Django+Js並利用表單實現檔案上傳

這段程式碼適用於利用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())