保护用户上传的文件django

时间:2012-02-26 15:25:43

标签: python django

如何允许用户将文件上传到他们自己的用户指定文件夹,只看到他们上传的文件?我正在使用django文件传输。目前,它让我可以选择将媒体放入哪个文件,但我可以将其放在任何用户的文件中并查看每个用户的媒体。这是我的上传/ models.py:

from django.db import models
from django.contrib.auth.models import User, UserManager

def uploadmodel_file_upload_to(instance, filename):
    print 'instance.user.username = '+ str(instance.user.username)
    return 'uploads/%s/%s' % (instance.user.username, filename)

class UploadModel(models.Model):
    user = models.ForeignKey('auth.user')
    file = models.FileField(upload_to=uploadmodel_file_upload_to)

1 个答案:

答案 0 :(得分:5)

uploadmodel_file_upload_to返回相对路径。要构建完整路径,django会预置settings.MEDIA_ROOT。 MEDIA_ROOT应该是公众可读的。

因此我们要将文件保存在MEDIA_ROOT之外。将这样的内容添加到settings.py:

import os.path
PROJECT_ROOT=os.path.abspath(os.path.dirname(__file__))
PROTECTED_MEDIA_ROOT=os.path.join(PROJECT_ROOT, 'protected_uploads')

现在您可以更新uploadmodel_file_upload_to以返回绝对路径:

def uploadmodel_file_upload_to(instance, filename):
    return '%s/%s/%s' % (settings.PROTECTED_MEDIA_ROOT, instance.user.username,
        filename)

现在文件保存在/ project / path / protected_uploads中,我们需要添加一个视图来提供它,例如:

import os 
import mimetypes

from django import shortcuts
from django import http
from django.conf import settings
from django.views.static import was_modified_since
from django.utils.http import http_date

from .models import *

def serve_upload(request, upload_id):
    upload = shortcuts.get_object_or_404(UploadModel, pk=upload_id)
    fullpath = upload.file.path

    if request.user != upload.user:
        return http.HttpResponseForbidden()

    statobj = os.stat(fullpath)
    mimetype, encoding = mimetypes.guess_type(fullpath)
    mimetype = mimetype or 'application/octet-stream'
    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              statobj.st_mtime, statobj.st_size):
        return http.HttpResponseNotModified(mimetype=mimetype)
    response = http.HttpResponse(open(fullpath, 'rb').read(), mimetype=mimetype)
    response["Last-Modified"] = http_date(statobj.st_mtime)
    response["Content-Length"] = statobj.st_size
    if encoding:
        response["Content-Encoding"] = encoding
    return response

还有一个网址:

url(r'serve_upload/(?P<upload_id>\d+)/$', 'serve_upload'),