2017-03-21 75 views
0

我想一個上傳的文件返回給客戶端後,返回文件給客戶。Django的REST框架:上傳

models.py

file = models.FileField(_('file'), db_index=True, null=True, blank=True, upload_to='files/') 

意見

class ContentInfoViewSet(viewsets.ModelViewSet): 
    queryset = ContentInfo.objects.all() 
    serializer_class = ContentInfoSerializer 
    http_method_names = ['get'] 

    @detail_route(methods=['get']) //this is just for testing 
    def files(self, request, pk=None): 
     return Response(pk, status=status.HTTP_200_OK) 

在這裏,我只是用 「文件」 路線嘗試。

當我嘗試得到「內容信息」。它很好地工作:

[ 
    { 
    "url": "http://127.0.0.1:8000/users/content-info/1/", 
    "id": 1, 
    "date": "2017-01-27T16:21:41.976289Z", 
    "title": "Hey Hey", 
    "image_url": "", 
    "content_url": "", 
    "file": null 
    }, 
    { 
    "url": "http://127.0.0.1:8000/users/content-info/3/", 
    "id": 3, 
    "date": "2017-03-21T12:09:32.984119Z", 
    "title": "NWE", 
    "image_url": "", 
    "content_url": "", 
    "file": "http://127.0.0.1:8000/users/content-info/files/BIAM-51.pdf" 
    } 
] 

但該URL不起作用。即使我使用授權得到。我不知道我做錯了什麼。 它沒有找到該頁面。而且它的邏輯,因爲它不是在urls.py(我的意思是http://127.0.0.1:8000/users/content-info/files/BIAM-51.pdf

該解決方案將是巨大的: pdf

當你打開鏈接,它顯示的PDF文件。我認爲這會發生,當我按照這個鏈接「http://127.0.0.1:8000/users/content-info/files/BIAM-51.pdf

+0

您正在使用Django的REST框架嗎? 也許[此帖](http://stackoverflow.com/questions/2294507/how-to-return-static-files-passing-through-a-view-in-django)將有助於 – code22

+0

呀,對不起,我忘了瞄準它。 –

+0

有沒有更好的方法來做到這一點? (即使我不使用fileField)我只想在瀏覽器中顯示文件。問題的關鍵是,我的東東,顯示無論是HTML,PDF或MP3 ......,並與內容類型,我得指定類型 –

回答

0

AS code22說,我能夠做到這一點與media_root,現在它真的很好。

我在項目中創建文件夾「媒體」。

proj 
|---proj 
|---media 
|---static 
|---app 

然後,我在車型都增加了這settings.py

MEDIA_URL = '/media/' 
MEDIA_ROOT = os.path.join(BASE_DIR, "media/") 

這在urls.py(整個項目)

from proj import settings 
from django.views.static import serve 

urlpattern = [ 
    ... 
    url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), 
] 

。 py

file = models.FileField(_('file'), db_index=True, null=True, blank=True, upload_to='files/') 

然後python3 manage.py makemigrationspython3 manage.py migrate

和文件(載之後)是在這裏:http://api.mydomain.com/media/files/myfile.pdf",僅此而已:)