Python 之檔案上傳

來源:互聯網
上載者:User

標籤:return   post   info   nqa   cti   init   charset   multipart   render   

 基於form表單提交
#  需要指定form-data,不能直接拼索引值對

可以指定name照片存在位置

 

views.py

from django.shortcuts import render,redirect,HttpResponse# Create your views here.import osdef index(request):    if request.method=="POST":        print(request.POST)  # post裡面只放索引值對 # < QueryDict: {‘csrfmiddlewaretoken‘:# [‘hS5bYNIkbNqazL7svWKxwrJXXY5sftIR1mxrMUMqox9diZS4bwz7Nn183Um8H0U8‘], ‘user‘: [‘6666‘], ‘f‘: [‘vzh.jpg‘]} >        print(request.FILES)        # <MultiValueDict: {‘f‘: [<InMemoryUploadedFile: vzh.jpg (image/jpeg)>]}>        obj = request.FILES.get("f")  # 取出上傳檔案的對象        name = obj.name  # 具體檔案的名字        f_write = open(os.path.join("app01","static","img",name),"wb")   #  如果想要將檔案存在某個具體的位置,將路徑拼接出來,再加上name                                    #  如果只放name ,那麼檔案會存在當前的根目錄下        for line in obj:  # 取出每一行的資料            f_write.write(line)        return HttpResponse("111")    return render(request,"index.html")def put(request):    return HttpResponse("ok")
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>Title</title></head><body><h3>基於form表單上傳檔案</h3>{# form-data類型可以上傳檔案#}<form action="" method="post" ENCTYPE="multipart/form-data">    {% csrf_token %}    <p><input type="text" name="user"></p>    <p><input type="file" name="f"></p>    <input type="submit"></form></body></html>
index.html

注意點:

 form表單<form action="" method="post" ENCTYPE="multipart/form-data">需要加ENCTYPE="multipart/form-data"form-data是可以用來上傳檔案

 

Python 之檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.