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': '123456', 'data': 'hahahaha'} import json return HttpResponse(json.dumps(ret))
1.xmlHttpResquest
Title
2.jQuery
Title
3.iframe
Title
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 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 structure, instead of : for (var p of myFormData)
is equivalent to for (var p of myFormData.entries())
.
FormData对象用以将数据编译成键值对,以便用来发送数据。其主要用于发送表单数据,但亦可用于发送带键数据(keyed data),而独立于表单使用。如果表单
enctype
属性设为multipart/form-data ,则会使用表单的方法来发送数据,从而,发送数据具有同样形式。
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发送数据
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){ //... } }}
上传至指定目录
settings.py文件 MEDIA_URL = "/media/"MEDIA_ROOT = os.path.join(BASE_DIR, "media")
然后在project的目录下创建文件夹"media"