简体   繁体   English

如何通过单击 Django 中的按钮上传文件?

[英]How to upload a file on click of a button in Django?

I have a requirement to upload a zip file with the click of an upload or save button.我需要通过单击上传或保存按钮来上传 zip 文件。 Then, when the user clicks on the "run" button, the uploaded file should get processed.然后,当用户点击“运行”按钮时,上传的文件应该得到处理。

I created a simple form and could write code to upload a file when the submit button was clicked, as shown below.我创建了一个简单的表单,可以编写代码在单击提交按钮时上传文件,如下所示。

if request.method=='POST':
   upload_request=UploadFile()
   upload_request.file=request.FILES['file_upload']
   upload_request.save()

Template:模板:

<form method="post" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" required name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br>           
    <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1">
</form> 

But how do I have a save functionality (a file should be uploaded) before submitting the form?但是在提交表单之前我如何拥有保存功能(应该上传文件)?

I am new to Django. Please give me some insights.我是Django的新手。请给我一些见解。

#try this #尝试这个

   from django.shortcuts import render, redirect
   from django.core.files.storage import default_storage
   from django.core.files.base import ContentFile

   def upload_zip_file(request):
        if request.method == 'POST':
            file = request.FILES['file']
            if (file.name.endswith('.zip') or file.name.endswith('.rar') or
                    file.name.endswith('.7z') or file.name.endswith('.gz')):
               path = default_storage.save('tmp/' + file.name, ContentFile(file.read()))
               return redirect('success')
               return render(request, 'upload.html')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM