如果新文件名与已经上传的文件名相似,我该如何覆盖该文件?如果我可以取file.name并删除任何带有此名称的文件,然后存储此文件,也适用于任何。任何方法都可以,请帮忙这是我的视图。py
from django.shortcuts import render
from django.views.generic import TemplateView
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse
import requests
from geopy.distance import geodesic as GD
import pandas as pd
from subprocess import run,PIPE
from .forms import UploadFileForm
from django.core.files.storage import FileSystemStorage
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
正如您所提到的,删除具有当前文件名的现有文件是可以的,您可以使用以下命令:
import os
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
name = str(file.name).replace("\", "/")
if os.path.exists(name):
os.remove(name)
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
另外,您可以重命名旧文件(通过在原始名称的末尾添加重命名时间)并以其名称保存新文件:
import os
from datetime import datetime
def content_file_name(filename):
file_root, file_ext = os.path.splitext(filename)
return f'{file_root}_{datetime.utcnow().time()}{file_ext}'
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
name = str(file.name).replace("\", "/")
if os.path.exists(name):
os.rename(src=name, dst=content_file_name(name))
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})
另外,您可以将每个文件的上传时间保存在其名称中:
import os
from datetime import datetime
def content_file_name(filename):
file_root, file_ext = os.path.splitext(filename)
return f'{file_root}_{datetime.utcnow().time()}{file_ext}'
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
file = request.FILES['file']
file.name = content_file_name(file.name)
fs = FileSystemStorage()
fs.save(file.name, file)
else:
form = UploadFileForm()
return render(request, 'upload.html', {'form':form})