实现文件上传的多种方法
实现文件上传的多种方法
一、Form表单上传
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>上传文件</title> </head> <body> <form action="/update.html/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user"> <div style="position:relative;"> <a>选择文件</a> <input type="file" name="img" style="opacity:0;position:absolute;top:0;left:0;height:16px;width:64px;"> </div> <input type="submit" value="提交"> </form> </body> </html>
def update(request): if request.method=="GET": return render(request,'update.html') else: img=request.FILES.get('img') if img: print(img.name) print(img.size) f = open(img.name, "wb") for line in img.chunks(): f.write(line) f.close() return HttpResponse('上传成功') else: return HttpResponse('选择上传文件')
二、AJAX上传
HTML - XMLHttpRequest
获取数据: var fileObj = document.getElementById("img").files[0];
封装数据: var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); 注意:FormData是个用来封装数据的。
创建XMLHttpRequest: var xhr = new XMLHttpRequest();
发送数据:
xhr.open("post", '/index', true); xhr.send(form);
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <input type="file" id="img" /> <input type="button" onclick="UploadFile();" /> <script> function UploadFile(){ var fileObj = document.getElementById("img").files[0]; var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); var xhr = new XMLHttpRequest(); xhr.open("post", '/index', true); xhr.send(form); } </script> </body> </html> HTML - XMLHttpRequest
HTML - jQuery
1.这里使用ajax进行数据提交
2.需要加上这两条
processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <input type="file" id="img" /> <input type="button" onclick="UploadFile();" /> <script> function UploadFile(){ var fileObj = $("#img")[0].files[0]; var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); $.ajax({ type:'POST', url: '/index', data: form, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function(arg){ console.log(arg); } }) } </script> </body> </html> HTML - jQuery
HTML - iframe
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <form id="my_form" name="form" action="/index" method="POST" enctype="multipart/form-data" > <div id="main"> <input name="fff" id="my_file" type="file" /> <input type="button" name="action" value="Upload" onclick="redirect()"/> <iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe> </div> </form> <script> function redirect(){ document.getElementById('my_iframe').onload = Testt; document.getElementById('my_form').target = 'my_iframe'; document.getElementById('my_form').submit(); } function Testt(ths){ var t = $("#my_iframe").contents().find("body").text(); console.log(t); } </script> </body> </html>
演示图片上传功能(iframe+From)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load staticfiles %} </head> <body> <!--FormData文件上传--> <script src="{% static '/js/jquery/jquery-3.3.1.js' %}"></script> <iframe style="" id="iframe" name="ifra"></iframe> <form id="fm" action="/upload_img.html/" method="post" enctype="multipart/form-data" target="ifra"> <input type="file" name="File" onchange="uploadFile();"> </form> <h3>预览</h3> <div id="preview"> </div> <script> function uploadFile(){ document.getElementById('iframe').onload=reloadIframe; document.getElementById('fm').submit(); } function reloadIframe(){ var content=this.contentWindow.document.body.innerHTML; var obj=JSON.parse(content); console.log(obj); var tag=document.createElement('img'); tag.src='http://127.0.0.1:8080/'+obj.data; console.log(obj.data); console.log(tag.src); $('#preview').empty().append(tag); } </script> </body> </html>
from django.shortcuts import render, HttpResponse, redirect import json import os import uuid def upload_img(request): nid = str(uuid.uuid4()) ret={'status':True,'data':None,'message':None} obj=request.FILES.get('File') file_path=os.path.join('static',nid+obj.name) print(file_path) print(1) f=open(file_path,'wb') for line in obj.chunks(): f.write(line) f.close() ret['data']=file_path return HttpResponse(json.dumps(ret))