【问题标题】:Save a picture in S3 from a temporary URL从临时 URL 在 S3 中保存图片
【发布时间】:2013-12-28 07:11:39
【问题描述】:

我正在开发一个关于 ruby​​ on rails 的网站,用户可以通过 paperclip 上传图片,它存储在 amazon S3 中。之后,他们可以通过 aviary 修改图片。但是当我想保存新图片时,aviary 只是给了我一个临时 URL,我可以在其中获取修改后的图片。

回形针可以吗?我不认为它可以从 URL 中保存图片并将其存储到 S3 中?

我已经搜索了一周,但我不知道最好的方法。我读过filepicker,但在 S3 文件中存储数据的帐户不是免费的...

我终于听说了这个 s3 https://github.com/qoobaa/s3,但我不明白如何使用它。我已经安装了 gem s3,但是当我设置 require 's3' 时,它无法识别。

什么是最好的?

【问题讨论】:

  • 没人知道吗?我正在尝试使用回形针,但我遇到了很多麻烦才能使其正常工作
  • 如果它仍然相关,请在下面查看我的答案 - 最新的 Paperclip 版本具有此功能

标签: ruby-on-rails amazon-s3 paperclip filepicker.io aviary


【解决方案1】:

您为什么不将 Aviary 生成的 URL 传递到您的服务器并从那里上传新照片?下面的代码在 Python/Django 中执行此操作:

@login_required    
@csrf_exempt
def upload_from_url(request):
    origin_url = request.POST.get("origin_url")
    name = request.POST.get("name")

    try:
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        bucket_name = settings.AWS_UGC_STORAGE_BUCKET_NAME
        bucket = conn.get_bucket(bucket_name)
        k = Key(bucket)

        k.key = name   
        file_object = urllib2.urlopen(origin_url)
        fp = StringIO.StringIO(file_object.read())
        k.set_contents_from_file(fp)

        return HttpResponse("Success")
    except Exception, e:
        return HttpResponse(e, mimetype='application/javascript')

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    自从回答了这个问题以来,Paperclip 已经成熟了很多。如果您想通过传递 URL 来保存文件,从 Paperclip v3.1.4 开始,您只需将 URL 分配给 Paperclip 附件属性即可。

    假设我有一个班级User,我的附件名为avatar。我们的User 模型中将包含以下内容:

    has_attached_file :avatar
    
    # Validate the attached image is image/jpg, image/png, etc
    # This is required by later releases of Paperclip
    validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
    

    在我们看来,我们可以定义一个隐藏字段来接受从 Aviary 接收到的临时 URL:

    = f.hidden_field :avatar, id: 'avatar'
    

    我们可以使用 Aviary onSave 回调来设置这个隐藏字段的值:

    var featherEditor = new Aviary.Feather({
      apiKey: '#{ENV['AVIARY_KEY']}',
      onSave: function(imageID, newURL) {
        var img = document.getElementById(imageID);
        img.src = newURL;
    
        var avatar = document.getElementById('avatar');
        avatar.value = newURL;
        featherEditor.close();
      }
    });
    

    在onSave中,你可以使用AJAX更新User对象,使用jQuery的.submit()提交表单,或者让用户在需要的时候提交。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多