django文件上传
定义一个包含FileFiled的类ModelWithFileField,其中upload字段的upload_to参数表示上传的文件存放在什么地方
class ModelWithFileField(models.Model): filename = models.CharField(max_length=100, verbose_name="文件名称") upload_date = models.DateField(verbose_name='上传日期') upload = models.FileField(upload_to='UPLOADFILES/') 原文链接:https://blog.csdn.net/dingrutao/article/details/116302190
定义一个form用于上传文件,form字段为FileField
class UploadFileForm(forms.Form): file = forms.FileField(label="选择文件")
定义一个view上传文件视图,首先实例form,返还给页面,选择一个文件,如果form判断有效则实例一个ModelWithFileField,分别保持文件和数据库
def upload_file(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): #获取form上传的文件 filename = request.FILES['file'].name #实例化文件类 insintanse = ModelWithFileField(upload=request.FILES['file'],filename=filename,upload_date=datetime.date.today()) insintanse.save() return HttpResponse("ok") else: return render(request, "upload.html", {"form": form}) else: form = UploadFileForm(request.POST, request.FILES) return render(request, "upload.html", {"form":form})
在urls中注册各个url
urlpatterns = [ path('index/', views.index, name='index'), path("upload/", views.upload_file, name='文件上传'), path("delete/<int:id>", views.delete_file, name='文件删除'), path("download/<int:id>", views.download_file, name="下载文件") ]
文件预览
定义预览视图
def index(request): #查询所有结果 files = ModelWithFileField.objects.all() return render(request, "index.html",{ 'files':files })
文件删除和下载
删除视图和下载视图,通过传入id来查找文件
def delete_file(request, id): #通过id查找到文件,删除存储文件及数据库中记录 fileid = ModelWithFileField.objects.get(id=id) filepath = fileid.upload.file.name os.remove(filepath) fileid.delete() return HttpResponseRedirect('/loadfile/index/') def download_file(request, id): filepath = ModelWithFileField.objects.get(id=id).upload.file.name filename = filepath.split("/")[-1] file = open(filepath, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{}"'.format(filename) return response
通过两个按钮实现文件删除,下载
<input type="button" value="删除" onclick="delete_file({{ file.id }})"> <input type="button" value="下载" onclick="download_file({{ file.id }})"> <script> function delete_file(id) { var r = confirm("是否删除") if (r == true){ alert("已删除") location.href = '/loadfile/delete/' + id } else { } } function download_file(id) { location.href = '/loadfile/download/' + id } </script>
标签:文件,form,删除,request,upload,django,file,上传,id From: https://www.cnblogs.com/mengdie1978/p/17342701.html