2013-02-28 116 views
1

我有一個圖片字段使用django-rest-framework如何處理通過API上傳圖片?django-rest-framework和上傳圖片

有沒有什麼例子?

models.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) 
+1

http://stackoverflow.com/questions/ 11398696/upload-image-of-imagefield-with-djangorestframework-using-json-and-test-this-wit – catherine 2013-02-28 15:38:06

回答

0

像場不存儲圖像,而是它的鏈接。你有設置MEDIA_URL嗎?例如MEDIA_URL ='/ media /'如果你在本地主機上運行,​​你應該在localhost/media/profiles/image_name.png上找到鏡像

2

最後,我可以使用Django上傳圖像。 這是我工作的代碼

views.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) 

urls.py

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

捲曲要求上傳

curl -X POST -S -H -u "admin:password" -F "[email protected];type=image/jpg" 127.0.0.1:8000/resourceurl/imageUpload 
+0

難道你沒有面對'關閉文件'的I/O操作? – andi 2015-03-03 13:37:05

+0

這是我的錯,因爲我使用了'TemporaryFileUploadHandler'而不是默認值。 – andi 2015-03-03 13:38:40