首页 > 代码库 > Django实现文件的上传
Django实现文件的上传
需求:自己写一个文件上传功能
代码:
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="http://www.mamicode.com/上传" /> </form> </body> </html>
运行结果:
Django实现文件的上传
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。