三种ajax上传文件方法
1. XMLHttpRequest(原生ajax)
<input class="file" type="file" id="fafafa" name="fileupload" />
<input type="button" value="提交XHR" onclick="xhrSubmit();"/>
<script type="text/javascript">
function xhrSubmit() {
{# $('#fafafa')[0]注意这儿的写法#} var file_obj = document.getElementById('fafafa').files[0]; var fd = new FormData(); fd.append('fafafa',file_obj); xhr = new XMLHttpRequest(); xhr.open('POST', '/upload_file/', true) xhr.send(fd); xhr.onreadystatechange = function () { //后端接受完毕 if(xhr.readyState == 4){ var obj = JSON.parse(xhr.responseText); console.log(obj); } }; }
</script>
2.JQueryAjax
<input type="button" value="jQuery ajax提交" onclick="jqSubmit();"/> <script type="text/javascript" src="/static/jquery-1.11.1.js"></script> <script type="text/javascript"> 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 //这儿的三个参数其实就是XMLHttpRequest里面带的信息。 success:function (arg,a1,a2) { console.log(arg); console.log(a1); console.log(a2); } }) }
</script>
3.伪ajax(iframe标签,既发送,也接受)
<form action="/upload_file/" method="POST" enctype="multipart/form-data" target="ifm1"> <iframe id="ifm1" name="ifm1"></iframe> {% csrf_token %} {# 这儿也可以设置自动提交,就把下面的提交去掉,加一个onchange="changeUpload();#} <input type="file" name="fafafa"/> <input type="submit" onclick="iframeSubmit()" name="提交"/> </form>
<div id="preview"></div> <!-- 处理预览 -->
<script type="text/javascript">
function iframeSubmit() { {# 等点了submit再加载load方法#} $('#ifm1').load(function () { var text = $('#ifm1').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj);
//处理预览 $('#preview').empty(); var imgTag = document.createElement('img'); {# 注意这儿的路径,得加上"/"#} imgTag.src = "/" + obj.data; $('#preview').append(imgTag); }) }
</script>
4. python后端处理
fafafa = request.FILES.get('fafafa') import os img_path = os.path.join('static/images',fafafa.name) # 下面这句等于 f = open(str(fafafa),mode='wb),并且添加了清理功能(f.close)。 with open(img_path,'wb') as f: for item in fafafa.chunks(): f.write(item)