Form表單上傳文件html
Ajax上傳文件python
僞造Ajax上傳文件ajax
<h3>form表單上傳文件</h3> <form action="/upload_file/" method="post" enctype="multipart/form-data"> <p><input type="file" name="upload_file_form"></p> <input type="submit"> </form>
注意:必須添加enctype="multipart/form-data屬性。瀏覽器
def index(request): return render(request,"index.html") def upload_file(request): print("FILES:",request.FILES) print("POST:",request.POST) return HttpResponse("上傳成功!")
XMLHttpRequest Level 2添加了一個新的接口FormData
.利用FormData對象
,咱們能夠經過JavaScript用一些鍵值對來模擬一系列表單控件,咱們還可使用XMLHttpRequest的send()
方法來異步的提交這個"表單".比起普通的ajax,使用FormData
的最大優勢就是咱們能夠異步上傳一個二進制文件.app
<h3>Ajax上傳文件</h3> <p><input type="text" name="username" id="username" placeholder="username"></p> <p><input type="file" name="upload_file_ajax" id="upload_file_ajax"></p> <button id="upload_button">提交</button> {#注意button標籤不要用在form表單中使用#} <script> $("#upload_button").click(function(){ var username=$("#username").val(); var upload_file=$("#upload_file_ajax")[0].files[0]; var formData=new FormData(); formData.append("username",username); formData.append("upload_file_ajax",upload_file); $.ajax({ url:"/upload_file/", type:"POST", data:formData, contentType:false, processData:false, success:function(){ alert("上傳成功!") } }); }) </script>
def index(request): return render(request,"index.html") def upload_file(request): print("FILES:",request.FILES) print("POST:",request.POST) return HttpResponse("上傳成功!")
<iframe> 標籤規定一個內聯框架。框架
一個內聯框架被用來在當前 HTML 文檔中嵌入另外一個文檔。異步
示例:post
<iframe src="http://www.baidu.com" width="1000px" height="600px"></iframe>
<h3>僞造Ajax上傳文件</h3> <form action="/upload_file/" method="post" id="form2" target="ifr" enctype="multipart/form-data"> <p> <iframe name="ifr" id="ifr"></iframe></p> <p><input type="file" name="upload_file"></p> <p><input type="text" name="user"></p> <input type="button" value="提交" id="submitBtn"> </form> <script> $("#submitBtn").click(function(){ $("#ifr").load(iframeLoaded); $("#form2").submit(); }); function iframeLoaded(){ alert(123) } </script>
def index(request): return render(request,"index.html") def upload_file(request): print("FILES:",request.FILES) print("POST:",request.POST) return HttpResponse("上傳成功!")