python之form表單上傳文件


文件上傳
-----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);

    } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM