Django-我需要实现拖放才能上传文件

时间:2018-12-21 07:45:38

标签: html django

我正在使用django开发一个小项目,我想实现拖放操作来上传文件。我已经从选择文件中实现了基本文件上传,并且工作正常。 请帮助我

我已经尝试过使用下面的代码来上传简单的文件,但我需要拖放操作,但我不知道该如何实现。

{% block content %}
  <div method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" name="myfile"><br><br>
  <input type="submit" value="upload">

{% endblock %}

Views.py

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage(location="test/uploadedmedia")
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'upload.html', {'uploaded_file_url': uploaded_file_url,"fileupload":"File uploaded successfully"})
    return render(request, 'upload.html')

我需要拖动文件并上传文件。

<html>
<head>
    <meta charset="utf-8">

    <title>Drag @drop</title>
<style>

.dropzone{
   width:300px;
   height:300px;
   border:2px dashed #ccc;
   color:#ccc;
   line-height:300px;
   text-align:center;

 }
.dropzone.dragover{
    border-color:#000;
    color:#000;
 }
 </style>
</head>
<body>

<div id="upload"></div>
<div class="dropzone" id="dropzone">Drop files here</div>

<script>
    (function(){
    var dropzone=document.getElementById('dropzone');


    dropzone.ondrop=function(e){
    e.preventDefault();
    this.className='dropzone';

    x=e.dataTransfer.files
    console.log(x)
    };

    dropzone.ondragover=function(){
    this.className='dropzone dragover';
    return false;
    };

    dropzone.ondragleave=function(){
     this.className='dropzone';

     return false;
     };
    }());

</script>
</body>
</html>

{% load static %}
{% block content %}
  <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="myfile" >
    <button type="submit" id="butto">Upload</button>
  </form>

  {% if uploaded_file_url %}
    <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
  {% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:0)

我找到了解决方法-

在您的放置区域中,只需在下面的代码中添加该代码-

  var dropzone=document.getElementById('dropzone');

    dropzone.ondrop=function(e){
    fileinput.files=e.dataTransfer.files
    e.preventDefault();