django中的Ajax文件上传
生活随笔
收集整理的這篇文章主要介紹了
django中的Ajax文件上传
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
主要介紹兩個(gè)
1.ajax文件上傳
2.寫路由器
?
3.創(chuàng)建對(duì)應(yīng)的函數(shù)
4.file_put.html代碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title></head> <body><h3>Ajax文件的上傳</h3> <div>{% csrf_token %}姓名<input type="text" id="user">文件<input type="file" name="file_obj" id="file"><input type="button" class="filebtn" value="提交"><p class="msg"></p> </div> <script src="/static/jquery.js"></script> <script>$(".filebtn").click(function () {var formdata=new FormData();formdata.append("file_obj",$("#file")[0].files[0]);formdata.append("user",$("#user").val());$.ajax({url: "/file_put/",type: "post",// Ajax上傳文件必備參數(shù)processData: false, // 不處理數(shù)據(jù)contentType: false, // 不設(shè)置內(nèi)容類型data: formdata,success: function (response) {console.log(response);if (response == "OK") {$(".msg").html("提交成功!")}}})})</script> </body> </html>5.上傳成功之后我們得下載下來
# 本地下載函數(shù) def file_put(request):print(request.POST)print(request.FILES)file_obj=request.FILES.get("file_obj")print(file_obj)# 文件對(duì)象有一個(gè)name屬性,獲取文件名稱字符串print(file_obj.name)path = file_obj.namepath = os.path.join(settings.BASE_DIR,"media","img",path) #進(jìn)行下載文件保存的地址拼接,注意的是,當(dāng)前項(xiàng)目里沒有 media文件和它下面的img文件,需要我們手動(dòng)的去創(chuàng)建 with open(path,"wb") as f: for line in file_obj: f.write(line) return HttpResponse("OK")成功之后,在你當(dāng)前的項(xiàng)目里就會(huì)有這個(gè)文件夾和你下載之后的文件
轉(zhuǎn)載于:https://www.cnblogs.com/lzqrkn/p/9880299.html
總結(jié)
以上是生活随笔為你收集整理的django中的Ajax文件上传的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css 设置背景色
- 下一篇: java按比例之原图生成缩略图