文件共享
Author: Publish: 2022年4月29日 16:57 Update: 2022年4月29日 16:57 Category: None Reading:78
url.py
urlpatterns = [
path('_file_handler/<path:file_path>',views.FileHandler.as_view(), name='file-handler'),
path('<path:file_path>', views.Home.as_view(), name='home'),
]
views.py
import shutil
from django.shortcuts import redirect, render, HttpResponse
from django.core.files import File
from django.urls import reverse
from django.views import View
from django.conf import settings
import os
# Create your views here.
class Home(View):
def get(self, request, *args, **kwargs):
request_path = kwargs.get('file_path')
home_path = settings.IPD_FILES_DIR
real_path = os.path.join(home_path, request_path)
# print(path)
if not os.path.exists(home_path):
os.makedirs(home_path)
try:
files = os.listdir(real_path)
except FileNotFoundError:
files = None
return render(request, 'ipdfile/home.html', {'files': files})
class FileHandler(View):
def get(self, request, *args, **kwargs):
request_path = self.handle_path(kwargs.get('file_path'))
delete_flag = request.GET.get('action')
print(delete_flag)
real_path = os.path.join(settings.IPD_FILES_DIR, request_path)
if delete_flag == 'delete':
p = self.delete_file(real_path)
return redirect(reverse('ipdfile:home', kwargs={'file_path': p}))
if os.path.isdir(real_path):
return redirect(reverse('ipdfile:home', kwargs={'file_path': request_path}))
file_name = real_path.split('/')[-1]
with open(real_path, 'rb') as f:
file = File(f)
response = HttpResponse(file.chunks(),
content_type='APPLICATION/OCTET-STREAM')
response['Content-Disposition'] = 'attachment; filename=' + file_name
response['Content-Length'] = os.path.getsize(real_path)
return response
def post(self, request, *args, **kwargs):
file = request.FILES.get("filename", None)
request_path = self.handle_path(kwargs.get('file_path'))
if not file:
return redirect(reverse('ipdfile:home', kwargs={'file_path': request_path}))
real_path = os.path.join(settings.IPD_FILES_DIR, request_path)
if not os.path.exists(real_path):
os.makedirs(real_path)
file_path = os.path.join(real_path, file.name)
with open(file_path, 'wb+') as f:
for chunk in file.chunks():
f.write(chunk)
return redirect(reverse('ipdfile:home', kwargs={'file_path': request_path}))
@staticmethod
def handle_path(path:str):
# /ipd/user/test or /ipd/user/test/
# return user/test
return path.strip('/')[4:]
@staticmethod
def delete_file(path:str):
# IpdFIles后的目录 方便重新定向
parent_path = os.path.dirname(path)[len(settings.IPD_FILES_DIR)+1:]
try:
if os.path.isdir(path):
# os.rmdir 验证文件夹是否为空 shutil.rmtree 不验证
shutil.rmtree(path)
else:
os.remove(path)
except OSError as error:
pass
return parent_path
template.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{% load static %}
<title>下载</title>
<script>
function confirm_delete(){
file_name = event.srcElement.dataset.path
delete_url = event.srcElement.dataset.url
var c = confirm("确认删除" + file_name)
if (c == true){
window.location.href= delete_url
}else{
}
}
</script>
</head>
<body>
<form action="{% url 'ipdfile:file-handler' request.path %}" enctype="multipart/form-data" method="post">
{% csrf_token %}
<input type="file" name="filename" value="">
<input type="submit" value="上传">
</form>
<ul>
{% for file in files %}
{% with request.path|add:'/'|add:file as real_path%}
<li style="margin-top:5px">
<a id='download' href="{% url 'ipdfile:file-handler' real_path %}">{{ file }}</a>
<a style='margin-left:250px' href="javascript:void(0)" onclick='confirm_delete()' data-path={{file}} data-url="{% url 'ipdfile:file-handler' real_path %}?action=delete">删除</a>
</li>
{% endwith %}
{% endfor %}
</ul>
</body>
</html>
Tags