django 无法上传图像

yfjy0ee7  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(97)

我尝试在Django中上传图像,但我不能。我不知道有什么问题。
错误:

django.core.exceptions.SuspiciousFileOperation: 
Detected path traversal attempt in '/media/uploads/87176296b7b2425e81e266eaed65019b.png'
Bad Request: /api/upload_file/
Bad Request: /api/upload_file/
[03/Aug/2023 17:47:52] "POST /api/upload_file/ HTTP/1.1" 400 17430

字符串
/API/上传文件:

def upload_file(request):
    request_file = request.FILES['file'] if 'file' in request.FILES else None
    if request_file is None:
        data={
            "error": "No file",
        }
        return Response(status=status.HTTP_400_BAD_REQUEST, data=data)
    if request_file.size > 20*1024*1024:
        data={
            "error": "Image file too large (>20mb)",
        }
        return Response(status=status.HTTP_400_BAD_REQUEST, data=data)
    allowed_file_types = ['jpeg', 'jpg', 'png']
    file_type = imghdr.what(request_file)
    if file_type not in allowed_file_types:
        data = {
            "error": "Invalid file type",
        }
        return Response(status=status.HTTP_400_BAD_REQUEST, data=data)
    upload = Upload(image=request_file)
    upload.save()
    data = {
        "upload_id": upload.id,
    }
    return Response(status=status.HTTP_200_OK, data=data)


Upload型号:

class Upload(models.Model):
    image = models.ImageField(
        verbose_name="Image",
        upload_to=path_and_rename_upload,
    )
    patient = models.ForeignKey(
        "users.Patient",
        verbose_name="Patient",
        related_name="uploads",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    upload_date = models.DateTimeField(
        verbose_name="Upload Date",
        auto_now_add=True,
    )

    def __str__(self):
        return self.image.name

@deconstructible
class PathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path

    def __call__(self, instance, filename) -> str:
        ext = filename.split(".")[-1]
        filename = f"{uuid4().hex}.{ext}".lower()
        return os.path.join(self.path, filename)

path_and_rename_upload = PathAndRename("/media/uploads")


我试着将路径设置为BASE_DIR/self.path/filename,但没有任何不同。
我的settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static')
]
if not DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
if not DEBUG:
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

2jcobegt

2jcobegt1#

尝试更改MEDIA_ROOT:

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

字符串

s4chpxco

s4chpxco2#

我改变了模型并创建了upload_to="media/uploads",然后在我的helper中编写了一个名为generate_filename(filename: str) -> str的函数,基本上做了与PathAndRename.__call__()相同的事情。然后在我看来,当保存上传:

upload = Upload()
upload.image.save(generate_filename(request_file.filename), request_file, save=False)
upload.save()

字符串
现在正在上传图像

相关问题