檔案上傳的幾種方法

來源:互聯網
上載者:User

標籤:get   臨時   res   mit   html   bsp   order   ack   padding   

  一、加enctype="multipart/form-data"<!DOCTYPE html><html><head>    <title>test</title></head><body><form action="/test/" method="post" enctype="multipart/form-data"> <!--如果不加這個的話,提交的資料會以索引值對提交-->    {% csrf_token %}    檔案:<input type="file" name=‘test‘><br>    <input type="submit" value="提交"></form></body></html>def test(request):    if request.method == ‘POST‘:        file = request.FILES.get(‘test‘)        with open(file.name, ‘wb‘) as f:            for line in file:                f.write(line)    return render(request, ‘test.html‘) 二、.chunks()def upload(request):    """    儲存上傳檔案前,資料需要存放在某個位置。預設當上傳檔案小於2.5M時,django會將上傳檔案的全部內容讀進記憶體。從記憶體讀取一次,寫磁碟一次。    但當上傳檔案很大時,django會把上傳檔案寫到臨時檔案中,然後存放到系統臨時檔案夾中。    :param request:    :return:    """    if request.method == "POST":        # 從請求的FILES中擷取上傳檔案的檔案名稱,file為頁面上type=files類型input的name屬性值        filename = request.FILES["file"].name        # 在項目目錄下建立一個檔案        with open(filename, "wb") as f:            # 從上傳的檔案對象中一點一點讀            for chunk in request.FILES["file"].chunks():                # 寫入本地檔案                f.write(chunk)        return HttpResponse("上傳OK")<!DOCTYPE html><html><head>    <title>test</title></head><body><form action="/test/" method="post">    {% csrf_token %}    檔案:<input type="file" name=‘test‘>    <input type="submit" value="提交"></form></body></html>  

檔案上傳的幾種方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.