ajax上传文件的三种方法
第一种xhr提交
function xhrSubmit(){
// $('#fafafa')[0]
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);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 接收完毕
var obj = JSON.parse(xhr.responseText);
console.log(obj);
}
};
xhr.send(fd);
}
第二种jQuery的ajax提交
function jqSubmit(){
// $('#fafafa')[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);
}
})
}
jQuery的ajax默认会做字符拼接,为了能够让文件正常上传定义如下:
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
第三种就是利用ifram来进行上传文件
HTML文件
<form id="form1" action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1">
<iframe id="ifm1" name="ifm1" style="display: none;"></iframe>
<input type="file" name="fafafa" onchange="changeUpalod();" />
{# <input type="submit" onclick="iframeSubmit();" value="Form提交"/>#}
</form>
在function只需要写这些就行
function iframeSubmit(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
})
}
views.py
def upload_file(request):
username = request.POST.get('username')
fafafa = request.FILES.get('fafafa')
import os
img_path = os.path.join('static/imgs/',fafafa.name)
with open(img_path,'wb') as f:
for item in fafafa.chunks():
f.write(item)
ret = {'code': True , 'data': img_path}
import json
return HttpResponse(json.dumps(ret))
文件上传预览
function changeUpalod(){
$('#ifm1').load(function(){
var text = $('#ifm1').contents().find('body').text();
var obj = JSON.parse(text);
$('#preview').empty();
var imgTag = document.createElement('img');
imgTag.src = "/" + obj.data;
$('#preview').append(imgTag);
});
$('#form1').submit();
}