1

我有一个使用django-rest-framework的图像字段如何处理通过 API 上传图像?

有没有例子?

模型.py

image = models.ImageField(
        upload_to="profiles",
        height_field="height",
        width_field="width",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    height = models.PositiveIntegerField(null=True, blank=True, editable=False)
    width = models.PositiveIntegerField(null=True, blank=True, editable=False)
4

2 回答 2

2

最后我可以使用 Django 上传图片。这是我的工作代码

视图.py

class FileUploadView(APIView):
# parser_classes = (MultiPartParser, FormParser, )
parser_classes = (FileUploadParser, )

# media_type = 'multipart/form-data'
# format = 'jpg'

def post(self, request, format='jpg'):
    up_file = request.FILES['file']
    destination = open('/Users/Username/' + up_file.name, 'wb+')
    for chunk in up_file.chunks():
        destination.write(chunk)
        destination.close()

    # ...
    # do some stuff with uploaded file
    # ...
    return Response(up_file.name, status.HTTP_201_CREATED)

网址.py

urlpatterns = patterns('', 
url(r'^imageUpload', views.FileUploadView.as_view())

curl请求上传

curl -X POST -S -H -u "admin:password" -F "file=@img.jpg;type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload
于 2015-02-24T13:52:16.933 回答
0

图像字段不存储图像,而是存储图像的链接。您是否在设置中设置了 MEDIA_URL?例如 MEDIA_URL = '/media/' 如果你在 localhost 上运行,你应该在 localhost/media/profiles/image_name.png 找到图像

于 2013-02-28T17:24:40.083 回答