Django 练习班级管理系统八 -- 上传文件
程序员文章站
2024-02-01 17:35:52
Form表单上传文件 修改 views.py 修改 models.py 在 templates 下添加 upload.html 文件,内容如下 修改 urls.py 重新生成数据库 Ajax 上传文件 修改 upload.html 文件 修改 views.py 文件 基于iframe实现form上传 ......
form表单上传文件
修改 views.py
import os def upload(request): if request.method == 'get': img_list = models.img.objects.all() return render(request, 'upload.html', {'img_list': img_list}) elif request.method == 'post': name = request.post.get('user') obj = request.files.get('fafafa') # 保存上传的文件 file_path = os.path.join('static', 'upload', obj.name) f = open(file_path, 'wb') for chunk in obj.chunks(): f.write(chunk) f.close() models.img.objects.create(path=file_path) # 返回并刷新页面 return redirect('upload.html')
修改 models.py
class img(models.model): path = models.charfield(max_length=128)
在 templates 下添加 upload.html 文件,内容如下
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> </head> <body> <form method="post" action="/upload.html" enctype="multipart/form-data"> <input type="text" name="user" /> <input type="file" name="fafafa" /> <input type="submit" value="提交" /> </form> <div> {% for item in img_list %} <img style="height: 200px; width: 200px;" src="/{{ item.path }}"> {% endfor %} </div> </body> </html>
修改 urls.py
# 添加 re_path('upload.html', views.upload),
重新生成数据库
python manage.py makemigrations python manage.py migrate
ajax 上传文件
修改 upload.html 文件
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <style> .container img{ width: 200px; height: 200px; } </style> </head> <body> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <input type="file" id="img" /> <input type="button" value="提交xml" onclick="uploadxml()" /> <input type="button" value="提交jq" onclick="uploadjq()" /> <script src="/static/jquery.min.js"></script> <script> function uploadxml() { var dic = new formdata(); // 通过formdata构造函数创建一个空对象 dic.append('user', 'v1'); // 通过append()方法在末尾追加 key 为 user 值为 v1 的数据 dic.append('fafafa', document.getelementbyid('img').files[0]); var xml = new xmlhttprequest(); xml.open('post', '/upload.html', true); // 参数说明: 请求方式;请求路径;是否异步处理,true为异步 xml.onreadystatechange = function () { // readystate 改变时触发 if(xml.readystate == 4){ // xml.readystate: xmlhttprequest对象的状态,等于4表示数据已经接收完毕。 var obj = json.parse(xml.responsetext); // responsetext 服务器接收到的响应体(不包括头部) if(obj.status){ var img = document.createelement('img'); // 创建一个元素 img.src = "/"+obj.path; document.getelementbyid('imgs').appendchild(img); } } }; xml.send(dic); // 发送 http 请求,使用传递给 open() 方法的参数,以及传递给该方法的可选请求体。 } function uploadjq() { var dic = new formdata(); dic.append('user', 'v1'); dic.append('fafafa', document.getelementbyid('img').files[0]); $.ajax({ url: 'upload.html', type: 'post', data: dic, processdata: false, // jquery不要去处理发送的数据 contenttype: false, // jquery不要去设置content-type请求头 datatype: 'json', success: function (arg) { // 响应的数据是 arg if(arg.status){ var img = document.createelement('img'); img.src = "/" + arg.path; $('#imgs').append(img); } } }) } </script> </body> </html>
修改 views.py 文件
import os import json def upload(request): if request.method == 'get': img_list = models.img.objects.all() return render(request, 'upload.html', {'img_list': img_list}) elif request.method == 'post': user = request.post.get('user') obj = request.files.get('fafafa') file_path = os.path.join('static', 'upload', obj.name) f = open(file_path, 'wb') for chunk in obj.chunks(): f.write(chunk) f.close() models.img.objects.create(path=file_path) ret = {'status': true, 'path': file_path} # 返回响应数据是字典 return httpresponse(json.dumps(ret))
基于iframe实现form上传文件
修改 upload.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <style> .container img{ width: 200px; height: 200px; } </style> </head> <body> <!-- <h1>测试iframe功能</h1> <input type="text" id="url" /> <input type="button" value="点我" onclick="iframechange();" /> <iframe id="ifr" src=""></iframe> <hr/> --> <h1>基于iframe实现form提交</h1> <!-- 表单提交的 target 为 iframe_2 --> <form action="/upload.html" method="post" target="iframe_2" enctype="multipart/form-data"> <!-- onload 事件的用处: 当页面载入完毕后执行javascript代码 --> <iframe style="display: none" id="iframe_1" name="iframe_2" src="" onload="loadiframe();"></iframe> <input type="text" name="user" /> <input type="file" name="fafafa" /> <input type="submit" /> </form> <div class="container" id="imgs"> {% for img in img_list %} <img src="/{{ img.path }}"> {% endfor %} </div> <input type="file" id="img" /> <input type="button" value="提交xml" onclick="uploadxml()" /> <input type="button" value="提交jq" onclick="uploadjq()" /> <script src="/static/jquery.min.js"></script> <script> function uploadxml() { var dic = new formdata(); dic.append('user', 'v1'); dic.append('fafafa', document.getelementbyid('img').files[0]); var xml = new xmlhttprequest(); xml.open('post', '/upload.html', true); xml.onreadystatechange = function () { if(xml.readystate == 4){ var obj = json.parse(xml.responsetext); if(obj.status){ var img = document.createelement('img'); img.src = "/"+obj.path; document.getelementbyid('imgs').appendchild(img); } } }; xml.send(dic); } function uploadjq() { var dic = new formdata(); dic.append('user', 'v1'); dic.append('fafafa', document.getelementbyid('img').files[0]); $.ajax({ url: 'upload.html', type: 'post', data: dic, processdata: false, contenttype: false, datatype: 'json', success: function (arg) { if(arg.status){ var img = document.createelement('img'); img.src = "/" + arg.path; $('#imgs').append(img); } } }) } function iframechange() { var url = $('#url').val(); $('#ifr').attr('src', url); } function loadiframe() { var str_json = $('#iframe_1').contents().find('body').text(); //根据view.py 的定义,服务端返回的内容为:{"status": true, "path": "static\\upload\\1.png"} var obj = json.parse(str_json); if (obj.status){ var img = document.createelement('img'); img.src = "/" + obj.path; $('#imgs').append(img); } } </script> </body> </html>