生活随笔
收集整理的這篇文章主要介紹了
文件上传三种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
需求
上傳圖片在頁面顯示
?
Form表單上傳
<!DOCTYPE html>
<html?lang="en">
<head>
??<meta?charset="UTF-8">
??<title>Title</title>
</head>
<body>
??<form?method="POST"?action="/upload.html"?enctype="multipart/form-data">
? ? ??<input?type="text"?name="user"?/>
? ? ??<input?type="file"?name="fafafa"?/>
? ? ??<input?type="submit"?value="提交"?/>
??</form>
??<div>
? ? ? {% if img %}
? ? ? ? ??<img?style="height: 200px;width: 200px;"?src="/{{ img }}"?/>
? ? ? {% endif %}
??</div>
??<script?src="/static/jquery-2.1.4.min.js"></script>
??
</body>
</html>
//后臺代碼
from django.shortcuts import render
import os
def upload(request):
? if request.method == 'GET':
? ? ? return render(request,'upload.html')
? elif request.method == "POST":
? ? ? user = request.POST.get('user')
? ? ? fafafa = request.POST.get('fafafa')
? ? ? obj = request.FILES.get('fafafa')
? ? ? file_path = os.path.join('static','upload',obj.name)
? ? ? f = open(file_path, 'wb')
? ? ? for chunk in obj.chunks():
? ? ? ? ? f.write(chunk)
? ? ? f.close()
? ? ? ret = {'status': True, 'path': file_path}
? ? ? return render(request,"upload.html",{'img':file_path}) 缺點:上傳后整個頁面會刷新,不好
?
Ajax上傳
<!DOCTYPE html>
<html?lang="en">
<head>
??<meta?charset="UTF-8">
??<title>Title</title>
??<style>
? ? ??.container?img{
? ? ? ? ??width:?200px;
? ? ? ? ??height:?200px;
? ? ? }
??</style>
</head>
<body>
??<input?ID="v1"?name="user"?placeholder="用戶">
??<input?type="file"?name="fafafa"?id="img"?/>
??<input?type="button"?value="提交XML"?onclick="UploadXML()"?/>
??<input?type="button"?value="提交JQ"?onclick="Uploadjq()"?/>
??<div?id="imgs">
??</div>
</body>
??<script?src="/static/jquery-2.1.4.min.js"></script>
??<script>
? ? ??function?UploadXML()?{
? ? ? ? ??var?dic =?new?FormData();
? ? ? ? ? dic.append('user', $('#v1').val());
? ? ? ? ? dic.append('fafafa',?document.getElementById('img').files[0]);
? ? ? ? ??var?xml =?
轉載于:https://www.cnblogs.com/IT-Scavenger/p/9266512.html
總結
以上是生活随笔為你收集整理的文件上传三种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。