python文件上传的三种方式

时间:2022-05-20 17:23:11
def upload(request):
return render(request, 'upload.html') def upload_file(request):
username = request.POST.get('username')
fafafa = request.FILES.get('fafafa') with open(fafafa.name, 'wb') as f:
for item in fafafa.chunks():
f.write(item)
print(username)
ret = {'code': '', 'data': 'hahahaha'}
import json
return HttpResponse(json.dumps(ret))

views.py

1.xmlHttpResquest

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.file{
width: 100px;
height: 50px;
position: absolute;
z-index: 100;
opacity: 0;
} .upload{
width: 100px;
height: 50px;
position: absolute;
z-index: 90;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: blue;
text-align: center;
line-height: 50px;
border-radius: 30px;
color: white;
}
</style> <body>
<div style="position: relative;height: 50px;width: 100px;">
<input class="file" type="file" id="fafafa">
<a class="upload">上传</a>
</div>
<input type="button" value="xhr提交" onclick="xhrSubmit()"> <script src="/static/jquery-1.12.4.js"></script>
<script>
function xhrSubmit() {
var file_obj = document.getElementById('fafafa').files[0];
var fd = new FormData();
fd.append('username','root')
fd.append('fafafa',file_obj) var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload_file/',true);
<!--onreadystatechange可以监测xhr的状态变化-->
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.send(fd);
}
</script>
</body>
</html>

2.jQuery

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
.file{
width: 100px;
height: 50px;
position: absolute;
z-index: 100;
opacity: 0;
} .upload{
width: 100px;
height: 50px;
position: absolute;
z-index: 90;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: blue;
text-align: center;
line-height: 50px;
border-radius: 30px;
color: white;
}
</style> <body>
<div style="position: relative;height: 50px;width: 100px;">
<input class="file" type="file" id="fafafa">
<a class="upload">上传</a>
</div>
<input type="button" value="jQuery提交" onclick="jqSubmit()"> <script src="/static/jquery-1.12.4.js"></script>
<script>
function jqSubmit() {
{#var file_obj = $('fafafa').files[0];#}
var file_obj = document.getElementById('fafafa').files[0];
var fd = new FormData();
fd.append('username','root');
fd.append('fafafa',file_obj); $.ajax({
url: '/upload_file/',
type: 'post',
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success:function (arg,a1,a2) {
console.log(arg);
console.log(a1);
console.log(a2);
}
})
}
</script>
</body>
</html>

3.iframe

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
<!--这里添加iframe是由于需要有一个html接收"/upload_file/"方法返回的参数,一般为HttpResponse,所以这里使用iframe接收,
iframe一般设置为"display:none"将其隐藏-->
<iframe id='ifm1' name="ifm1"></iframe>
<input type="file" name="fafafa">
<input type="submit" onclick="iframeSubmit()" value="iframe提交">
</form> <script src="/static/jquery-1.12.4.js"></script>
<script>
function iframeSubmit() {
$('#ifm1').load(function () {
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text)
console.log(obj)
})
}
</script>
</body>
</html>

FormData

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

An object implementing FormData can directly be used in a for...of structure, instead of entries()for (var p of myFormData) is equivalent to for (var p of myFormData.entries()).

FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据。其主要用于发送表单数据,但亦可用于发送带键数据(keyed data),而独立于表单使用。如果表单enctype属性设为multipart/form-data ,则会使用表单的submit()方法来发送数据,从而,发送数据具有同样形式。

https://developer.mozilla.org/en-US/docs/Web/API/FormData

1、通过get(key)与getAll(key)来获取相对应的值

// 获取key为age的第一个值
formdata.get("age");
// 获取key为age的所有值,返回值为数组类型
formdata.getAll("age");

2、通过append(key,value)在数据末尾追加数据

//通过FormData构造函数创建一个空对象
var formdata=new FormData();
//通过append()方法在末尾追加key为name值为laoliu的数据
formdata.append("name","laoliu");
//通过append()方法在末尾追加key为name值为laoli的数据
formdata.append("name","laoli");
//通过append()方法在末尾追加key为name值为laotie的数据
formdata.append("name","laotie");
//通过get方法读取key为name的第一个值
console.log(formdata.get("name"));//laoliu
//通过getAll方法读取key为name的所有值
console.log(formdata.getAll("name"));//["laoliu", "laoli", "laotie"]

3、通过set(key, value)来设置修改数据

# key的值不存在,会添加一条数据
//通过FormData构造函数创建一个空对象
var formdata=new FormData();
//如果key的值不存在会为数据添加一个key为name值为laoliu的数据
formdata.set("name","laoli");
//通过get方法读取key为name的第一个值
console.log(formdata.get("name"));//laoli

4、通过has(key)来判断是否存在对应的key值

//通过FormData构造函数创建一个空对象
var formdata=new FormData();
//通过append()方法在末尾追加key为name值为laoliu的数据
formdata.append("name","laoliu");
//判断是否包含key为name的数据
console.log(formdata.has("name"));//true
//判断是否包含key为age的数据
console.log(formdata.has("age"));//false

5、通过delete(key)可以删除数据

//通过FormData构造函数创建一个空对象
var formdata=new FormData();
//通过append()方法在末尾追加key为name值为laoliu的数据
formdata.append("name","laoliu");
console.log(formdata.get("name"));//laoliu
//删除key为name的值
formdata.delete("name");
console.log(formdata.get("name"));//null

通过XMLHttpRequest发送数据

<form id="advForm">
<p>广告名称:<input type="text" name="advName" value="xixi"></p>
<p>广告类别:<select name="advType">
<option value="1">轮播图</option>
<option value="2">轮播图底部广告</option>
<option value="3">热门回收广告</option>
<option value="4">优品精选广告</option>
</select></p>
<p>广告图片:<input type="file" name="advPic"></p>
<p>广告地址:<input type="text" name="advUrl"></p>
<p>广告排序:<input type="text" name="orderBy"></p>
<p><input type="button" id="btn" value="添加"></p>
</form>

HTML

var btn=document.querySelector("#btn");
btn.onclick=function(){
var formdata=new FormData(document.getElementById("advForm"));
var xhr=new XMLHttpRequest();
xhr.open("post","http://127.0.0.1/adv");
xhr.send(formdata);
xhr.onload=function(){
if(xhr.status==200){
//...
}
}
}

JS

上传至指定目录

settings.py文件

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

然后在project的目录下创建文件夹"media"