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; 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{
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{
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>