Django檔案上傳執行個體

來源:互聯網
上載者:User

標籤:enc   rand   邏輯   錯誤   class   模版   file   name   cti   

近日在用Django架構開發過程中遇到上傳帳戶圖片問題,經多方搜尋資料,終於解決問題!

1.首先,在html模版中添加類似下面的代碼

12345 <form enctype="multipart/form-data" method="POST" action="/view/process/upload/file">    {% csrf_token %}    <input type="file" name="your_file"/>    <input type="submit" value="上傳檔案" /></form>

這裡需要注意一下幾點:

  1. form表單匯總一定要有enctype="multipart/form-data"屬性
  2. form需要以POST方式提交
  3. form的Action屬性對應views中處理upload上傳邏輯的函數
  4. 需要有csrf_token這個標籤,否則post無法提交
  5. 第一個<input>的類型為file,這是一個檔案選取器,name屬性很重要,因為後面通過此欄位取出檔案對象

 

2.接下來,編寫CGI邏輯

1234567891011121314 def process_upload_file(request):    # 擷取檔案    file_obj = request.FILES.get(‘your_file‘, None)    if file_obj == None:        return HttpResponse(‘file not existing in the request‘)         # 寫入檔案    file_name = ‘temp_file-%d‘ % random.randint(0,100000) # 不能使用檔案名稱,因為存在中文,會引起內部錯誤    file_full_path = os.path.join(UPLOAD_ROOT, file_name)    dest = open(file_full_path,‘wb+‘)    dest.write(file_obj.read())    dest.close()         return render_to_response(‘upload_result.html‘,{})

取用檔案的方式為:“file_obj = request.FILES.get(‘file‘, None)”。第一個參數”your_file”對應form中的第一個input標籤。然後,可以通過file_obj.name擷取檔案名稱,file_obj.read()方法擷取檔案內容。上傳的檔案放在記憶體中,所以此方法只適合小檔案上傳。

Django檔案上傳執行個體

相關文章

聯繫我們

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