在Django中接收文件並存儲


首先是一個views函數的例子


def get_user_profiles(request):
    if request.method == 'POST':
            myFile = request.FILES.get("filename", None)
            if myFile:
                dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
                destination = open(os.path.join(dir, myFile.name),
                                   'wb+')
                for chunk in myFile.chunks():
                    destination.write(chunk)
                destination.close()
            return HttpResponse('ok')

這是一個簡單的接收客戶端上傳的頭像文件並保存的例子,應該看過這個就已經大體會使用接收文件了

但是這里的filename是客戶端上傳的文件名,也可能是像下面這樣的表單


<input type="file" name="filename" />

如果不知道固定上傳的文件名,想要客戶端上傳什么文件就以其上傳的名字命名可以這么寫


def get_user_profiles(request):
    if request.method == 'POST':
        if request.FILES:
            myFile =None
            for i in request.FILES:
                myFile = request.FILES[i]
            if myFile:
                dir = os.path.join(os.path.join(BASE_DIR, 'static'),'profiles')
                destination = open(os.path.join(dir, myFile.name),
                                   'wb+')
                for chunk in myFile.chunks():
                    destination.write(chunk)
                destination.close()
            return HttpResponse('ok')

不過這個是通過輸出request.FILES試出來的,不知道是否有更合適的方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM