Django中的python文件上傳

1、上傳到本地

準備工做:

models中建立表:html

class Book(models.Model):
    name = models.CharField(
        max_length=40
    )
    icon = models.ImageField(
        upload_to="icons"  # 指定文件保存的路徑名 系統自動建立
    )

settings中配置存儲路徑前端

MEDIA_ROOT = os.path.join(BASE_DIR, "static/uploads")

生成一個不重複的文件名:數據庫

import uuid,hashlib

def get_unique_str():
    uuid_str = str(uuid.uuid4())
    md5 = hashlib.md5()
    md5.update(uuid_str.encode('utf-8'))
    return md5.hexdigest()

 

方法一(文件保存到本地和數據庫):

views視圖中的寫法:瀏覽器

def test1(req):
    if req.method == 'GET':
        return render(req, 'mybook.html',{'book_name':book.name,'icon':icon_url})
    name = req.POST.get('name')
    myfile = req.FILES.get('icon')
    book = Book.objects.create(name=name,icon=myfile)  #將數據存儲到Book表中
    return HttpResponse('OK')

前端頁面寫法:網絡

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/app/test1/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" name="name" placeholder="書名"><br>
    <input type="file" name="icon"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

拼接圖片的網絡路徑,可經過該路徑在瀏覽器上顯示出圖片app

 icon_url = "http://{}/static/uploads/{}".format(
            req.get_host(), #獲取訪問的域名加端口
            book.icon.url  #圖片的路徑字符串
        )

方法二(文件保存到本地):

views視圖中的寫法:post

from .myutil import get_unique_str
def test2(req):
    if req.method == 'GET':
        return render(req,'mybook.html')
    else:
        name = req.POST.get('name')
        myfile = req.FILES.get('icon')
        filename = get_unique_str()+'.'+myfile.name.split('.')[-1]

        # 文件路徑
        filepath = os.path.join(settings.MEDIA_ROOT,filename)
        f = open(filepath,'wb')
        for i in myfile.chunks():
            f.write(i)
        f.close()
        return HttpResponse('OK')

前端頁面的寫法:ui

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/app/test2/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" name="name" placeholder="書名"><br>
    <input type="file" name="icon"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

2、上傳到oss(***)

進入阿里雲OSS管理控制檯,找到如下信息阿里雲

 

views視圖中的寫法url

import oss2
from io import BytesIO
def upload_to_oss(req):
  if req.method == 'GET':
  return render(req,'mybook.html')

  # 將找到的信息填入下面空缺處
    endpoint = ''
    access_key_id = ''
    access_key_secret = ''
    bucket_name = ''
    bucket_name_host = ""
    # 生成一個認證對象
    auth = oss2.Auth(access_key_id, access_key_secret)

    bucket = oss2.Bucket(auth, endpoint, bucket_name)

    # 獲取文件
    f = req.FILES.get("icon")
    # 實例化io
    buf = BytesIO()
    # 寫入到內存
    for i in f.chunks():
        buf.write(i)
    # 調整指針到開頭
    buf.seek(0)

    # 上傳
    filename = get_unique_str() + "." + f.name.split(".")[-1]
    bucket.put_object(filename, buf.getvalue())return HttpResponse('ok')

 前端頁面寫法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/app/upload_to_oss/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="text" name="name" placeholder="書名"><br>
    <input type="file" name="icon"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

  圖片最終會被上傳到阿里雲OSS管理控制檯中你選擇的bucket的文件管理中。

相關文章
相關標籤/搜索