【问题标题】:Sending an image through an iPhone app to a django web service and sending it通过 iPhone 应用程序将图像发送到 django Web 服务并发送
【发布时间】:2014-06-19 05:51:37
【问题描述】:

我有一个 django 网络服务。我希望能够接受来自 iOS 应用程序的图像,将图像保存到数据库中(图像文件本身应该放在我的 s3 存储桶中)。

通过管理员保存它非常容易,您只需定义upload_to 并将存储桶设置为 static_url,但我找不到任何关于如何保存从应用程序发送的图像的示例/文档。

谁能指出我正确的方向或举个例子?

由于我的问题含糊不清,请提供更多信息:

class Image(models.Model):
    name = models.CharField(max_length = 255)
    caption = models.CharField(max_length = 255)
    image = models.ImageField(upload_to='uploads/',blank=True,null=True)
    rent_property = models.ForeignKey(RentProperty, related_name='Images')
    is_main_image = models.BooleanField(default=False)

setting.py

#Amazon Bucket
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = '################'
AWS_SECRET_ACCESS_KEY = '#####################'
AWS_STORAGE_BUCKET_NAME = 'string'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

这是我的图像类,我想做的是从应用程序中获取图像,将其保存到数据库和 S3 存储中,并将其链接到正确的外键。

我的麻烦在于了解如何在将信息保存到数据库的同时将文件保存到 S3。

【问题讨论】:

    标签: django amazon-s3 boto django-storage


    【解决方案1】:

    我在这里回答了一个非常相似的问题:Best way to upload image from Mobile to Django server,所以你的问题可能被视为重复。

    图像是否会链接到数据库对象(可能是图像模型)?

    如果是这样,添加到上面链接的代码:

    @csrf_exempt
    def handle_uploads(request):
        if request.method == 'POST':
            uploaded_file = request.FILES['file']
            file_name = uploaded_file.name
            # Write content of the file chunk by chunk in a local file (destination)
            with open('path/to/destination_dir/' + file_name, 'wb+') as destination:
                for chunk in uploaded_file.chunks():
                    destination.write(chunk)
            # Create your object
            obj = Image.objects.create(file_field='path/to/destination_dir/' + file_name)
            obj.save()
    
        response = HttpResponse('OK')
        return response
    

    希望这会有所帮助,

    编辑:


    我可能误解了你,如果你打算使用外部存储,你为什么要问如何保存图像?你的意思是你只想保存文件名?或者你想让 Django 无缝使用 S3 存储?我相信这是有据可查的https://docs.djangoproject.com/en/1.6/howto/custom-file-storage/,但上面的代码需要一些返工。

    不费吹灰之力就找到了:http://www.laurentluce.com/posts/upload-and-download-files-tofrom-amazon-s3-using-pythondjango/

    它似乎非常适合您想要实现的目标。只需将上传部分添加到上面的代码中,您就应该正确:)

    【讨论】:

    • 没错,我可能还没有解释我自己。我的主要问题是如何将图像“数据”存储到数据库中并将图像本身存储到 S3,就像我使用管理员保存时一样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多