文件上传
-----form表单上传文件
看下代码就完事了
def up_load(request): if request.method == "GET": 获取数据库的数据 imglist=models.Image.objects.all() return render(request, "upload.html",{"imageL":imglist}) elif request.method == "POST": user = request.POST.get("user") haha = request.POST.get("ha") # 上传图片 obj = request.FILES.get("ha") print(obj.name, obj.size) # f=open(obj.name,\'wb\') import os filepath = os.path.join("static","image", obj.name)#图片的路径 # f=open(os.path.join("upload",obj.name),\'wb\') #将路径存入数据库 models.Image.objects.create(path=filepath) f = open(filepath, \'wb\') for chunk in obj.chunks(): f.write(chunk) f.close() print(user, haha) return render(request, "upload.html")
html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/upload/" enctype="multipart/form-data"> <input type="text" name="user"/> <input type="file" name="ha"/> <input type="submit" value="提交"/> </form> <div> {#<img style="height: 200px;width: 200px; background: /static/image/1-1G1201AJ9.jpg" src=""/>#} {% for item in imageL %} <img style="height: 200px;width: 200px" src="/{{ item.path }}"/> {% endfor %} </div> </body> </html>
--------Ajax上传文件
悄悄的上传
- xmlHttpRequest
xml=new XMLHttpRequest();#定义一个对象 xml.open("post","/upload/",true)#以post方式传到url,true表示异步的。 xml.send("k1=v1;k2=v2")#字符串的形式发送
- jQuery
$.ajax({ url: data:{\'k1\':\'v1\',\'k2\':\'v2\'} }) FormData对象 可以承载字符串,也可以承载文件 dict=new FormData #创建了一个dict对象 dict.append(\'k1\',\'v1\'); #生成键值对 dict.append(\'k2\',\'v2\'); dict.append(\'hahahh\',文件对象);
--------基于form表单和iframe自己实现ajax请求
iframe实现局部刷新
<input type="text" id="url"/> <input type="button" value="点我" onclick="iframe_Change();"/> <iframe id="ifr" src=""></iframe> function iframe_Change() { var url=$(\'#url\').val(); $(\'#ifr\').attr(\'src\',url); }