前端代码:
<style> .upload{ display: inline-block;padding: 10px; background-color: brown; position: absolute; top: 0; bottom: 0; right: 0; left: 0; z-index: 90; } .file{ width: 100px;height: 50px;opacity: 0; position: absolute; top: 0; bottom: 0; right: 0; left: 0; z-index: 100; } </style> <body> <!--前端上传文件的代码 --> <div style="position: relative;width: 100px;height: 50px;"> <input class="file" type="file" id="fafafa" name="afafaf" /> <a class="upload">上传</a> </div> <!--前端通过XHR提交文件 --> <input type="button" value="提交XHR" onclick="xhrSubmit();" /> <!--前端通过jQuery提交文件--> <input type="button" value="提交jQuery" onclick="jqSubmit();" /> <hr/> <!--前端通过iframe提交文件--> <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> <div id="preview"></div> <script src="/static/jquery-1.12.4.js"></script> <script> //选中自动提交 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(); } //前端通过jQuery提交文件 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); } }) } //前端通过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); } function iframeSubmit(){ $(‘#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); }) } </script> </body>
后端接收文件,并返回值<views>接收
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))
原文地址:https://www.cnblogs.com/magictor/p/9098117.html
时间: 2024-10-09 03:38:34