经典文件上传方式
创建URL
from django.contrib import admin from django.urls import path from django.conf.urls import url from app01 import views urlpatterns = [ path('admin/', admin.site.urls), url("upload.html",views.upload), ]
创建一个简易上传页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="upload.html" method="post" enctype="multipart/form-data"> {% csrf_token %} <p><input type="text" name="user"></p> <p><input type="file" name="img"></p> <p><input type="submit" value="上传"></p> </form> </body> </html>
创建视图函数进行接收前端传入的文件
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect from django import forms from django.forms import fields # Create your views here. class UploadForm(forms.Form): user=fields.CharField() img=fields.FileField() def upload(request): if request.method=="GET": return render(request,"upload.html") else: obj=UploadForm(request.POST,request.FILES) if obj.is_valid(): user=obj.cleaned_data["user"] img=obj.cleaned_data["img"] # user=request.POST.get("user") # img=request.FILES.get("img") # print(request.POST) #获取以POST方式提交的数据 # print(request.FILES) #获取前端提交的文件 # print(img) #获取文件信息 # print(img.name) #获取文件名称 # print(img.size) #获取文件大小 f=open(img.name,"wb") for line in img.chunks(): f.write(line) f.close() return HttpResponse("ok")
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/187788.html