需求:自己写一个文件上传功能
代码:
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^upload.html$‘, views.upload), ]
views.py
from django.shortcuts import render from django.shortcuts import redirect from django.shortcuts import HttpResponse from app01 import models import os <strong>#实现文件上传功能</strong> def upload(request): if request.method == ‘GET‘: return render(request,‘upload.html‘) elif request.method == ‘POST‘: obj = request.FILES.get(‘fafafa‘) f = open(os.path.join(‘upload‘,obj.name),‘wb‘) for line in obj.chunks(): f.write(line) f.close() return HttpResponse(‘上传成功‘)
upload.html
<!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 %} <input type="file" name="fafafa" /> <input type="submit" value="上传" /> </form> </body> </html>
运行结果:
时间: 2024-11-09 00:31:14