1. 程式人生 > >HTML 上傳檔案

HTML 上傳檔案

上接簡單的 Django 專案 https://www.cnblogs.com/klvchen/p/10155538.html
這裡需要注意兩個地方:

  • 表單提交方式需要是 post
  • form 新增一個屬性為 enctype="multipart/form-data"

在 index.html 加入input 標籤

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>hello worlds</h1>
<form action="/klvchen/" method="post" enctype="multipart/form-data">
    <p><input type="file" name="upload"></p>
    <p><input type="submit" value="submit"></p>
</form>

</body>
</html>

修改 views.py

from django.shortcuts import render

def klvchen(req):
    print("前端資料: ", req.POST)
    print("file:", req.FILES)

    for item in req.FILES:
        obj = req.FILES.get(item)      # 獲取要寫入的檔案
        filename = obj.name            # 獲取檔名
        f = open(filename, 'wb')
        for line in obj.chunks():      # 分塊寫入
            f.write(line)
        f.close()

    return render(req, "index.html")

成功上傳檔案