gpt4 book ai didi

html - Django - 我需要实现拖放来上传文件

转载 作者:行者123 更新时间:2023-11-28 02:26:16 25 4
gpt4 key购买 nike

我正在使用 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 %}

最佳答案

我找到了解决方案-

在你的拖放区只需添加下面的代码-

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

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

关于html - Django - 我需要实现拖放来上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53880957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com