Django文件上传(经典上传方式)
经典文件上传方式
创建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")