0

我在我的项目中使用 django-storages。用例:我从 vue 应用上传文件。我的服务器端(使用 django rest 框架)处理这个请求并上传文件(我想上传图片和视频,主要是 png 和 mp4)。

我的文件模型:

from django.db import models
from storages.backends.sftpstorage import SFTPStorage
SFS = SFTPStorage()

class File(models.Model):
    class Meta:
        verbose_name_plural = "File"

    name = models.CharField(max_length=255)
    location = models.CharField(max_length=255)
    uploadDate = models.DateField()
    comment = models.CharField(max_length=255, null=True, blank=True)
    connectedTo = models.ForeignKey(
        "self", on_delete=models.CASCADE, null=True, blank=True)
    ghbwrzipgw = models.FileField(
        null=True, blank=True, storage=SFS)

    def __str__(self):
        return f'{self.name} (Upload Date: {self.uploadDate}, Connected To: {self.connectedTo})'

我的文件视图:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from measurement_db.models.file import File
from measurement_db.serializers.file import FileSerializer

@api_view(['GET'])
def FileList(request):
    file = File.objects.all()
    serializer = FileSerializer(file, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def FileDetail(request, pk):
    file = File.objects.get(id=pk)
    serializer = FileSerializer(file, many=False)
    return Response(serializer.data)


@api_view(['POST'])
def FileCreate(request):
    serializer = FileSerializer(data=request.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['PUT'])
def FileUpdate(request, pk):
    file = File.objects.get(id=pk)
    serializer = FileSerializer(instance=file, data=request.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['DELETE'])
def FileDelete(request, pk):
    file = File.objects.get(id=pk)
    file.delete()

    return Response(status=status.HTTP_200_OK)

还有我的一个片段settings.py

DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage'

SFTP_STORAGE_HOST = 'host'
SFTP_STORAGE_ROOT = 'root'
SFTP_STORAGE_PARAMS = {
    'port': 1234,
    'username': 'username',
    'password': 'pass',
    'allow_agent': False,
    'look_for_keys': False,
}
# SFTP_KNOWN_HOST_FILE = '~/.ssh/known_hosts'
SFTP_STORAGE_INTERACTIVE = False

我的问题是,下载后我无法访问文件。文件存储在服务器端,但是当我想从前端下载并打开它时,会出现错误,导致文件无法访问。

错误是:

GET /uploads/test.txt HTTP/1.1" 404 2856

我尝试了一些解决方案,链接如下:

已解决:带有 SFTP 的 Django-Storages:GET 请求失败

如何使用 django-storage sftp 下载文件?

这些都没有解决我的问题。我是使用 Django 的初学者,所以请尝试解释您的解决方案:)

4

0 回答 0