u_3.html文件
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>form表单形式的文件上传</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="/static/js/jquery.js"></script> <script> $(function () { $('button').click(function () { $.ajax({ url: $('#url').attr('href'), type: 'get', success: function (response) { $('#text').html(response) } }) }) }) </script> </head> <body> <div class="container"> <form action="{% url 'u_33' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="uploadfile"></label> 标题<input type="text" name="title" id="uploadfile"> 文件<input type="file" name="file_obj"> <input type="submit"> </form> </div> </body> </html>
view.py
from django.shortcuts import render,HttpResponse import json,os from bms import settings # Create your views here. def u_3(request): return render(request,'u_3.html') def u_33(request): # 打印键值对信息 print(request.POST) # 打印上传文件信息 print(request.FILES) # < MultiValueDict: {'file_obj': [ < InMemoryUploadedFile: 文档碎片2.html(text / html) >]} > # 取出file_obj对象 file_obj = request.FILES.get("file_obj") print(file_obj) # 文件对象有一个name属性,获取文件名称字符串 file_obj_name = file_obj.name print(file_obj_name) # 上传文件的存储路径 path = os.path.join(settings.BASE_DIR,'upload','media',file_obj_name) # 开始存储 with open(path,'wb') as f: # 循环上传文件,按行输出 for line in file_obj_name: # 按行写入存储文件 f.write(line) return HttpResponse('Upload Successful')
urls.py
from django.urls import path, re_path, include from upload import views urlpatterns = [ re_path('^u_3$', views.u_3, name='u_3'), re_path('^u_33$', views.u_33, name='u_33'), ]