jquery - 使用 JQuery 文件上传到亚马逊 S3 在客户端调整图像大小

标签 jquery ruby-on-rails file-upload amazon-s3 coffeescript

我已经在互联网上看到了一些例子,例如:thisthis one ,但我正在关注 RailsCast Episode #383 Uploading to Amazon S3当然,在视频的最后,他提到了使用 JavaScript 在客户端调整图像大小。 问题是,如果我按照他的例子,我无法实现。我正在使用 gem jquery-fileupload-rails

编辑:我注意到我缺少 JQuery-fileupload example to resize image page 所需的一些 JS ,但仍然不起作用。 我对 application.js

的要求
//= require jquery-fileupload/vendor/jquery.ui.widget
//= require jquery-fileupload/vendor/load-image
//= require jquery-fileupload/vendor/canvas-to-blob
//= require jquery-fileupload/jquery.iframe-transport
//= require jquery-fileupload/jquery.fileupload
//= require jquery-fileupload/vendor/tmpl
//= require jquery.fileupload-process
//= require jquery.fileupload-image
//= require jquery-fileupload/locale

我的posts.js.coffee http://pastebin.com/9sm7UtsP

jQuery ->
  $('#fileupload').fileupload
    add: (e, data) ->
      types = /(\.|\/)(gif|jpe?g|png)$/i
      file = data.files[0]
      if types.test(file.type) || types.test(file.name)
        data.context = $(tmpl("template-upload", file))
        $('#fileupload').append(data.context)
        data.submit()
      else
        alert("#{file.name} is not a gif, jpeg, or png image file")

    progress: (e, data) ->
      if data.context
        progress = parseInt(data.loaded / data.total * 100, 10)
        data.context.find('.bar').css('width', progress + '%')

    done: (e, data) ->
      file = data.files[0]
      domain = $('#fileupload').attr('action')
      path = $('#fileupload input[name=key]').val().replace('${filename}', file.name)
      to = $('#fileupload').data('post')
      content = {}
      content[$('#fileupload').data('as')] = domain + path
      $.post(to, content)
      data.context.remove() if data.context # remove progress bar

    fail: (e, data) ->
      alert("#{data.files[0].name} failed to upload.")
      console.log("Upload failed:")
      console.log(data)

我的upload_helper.rb(路径:apps/helpers) http://pastebin.com/VxAbiUft

module UploadHelper
  def s3_uploader_form(options = {}, &block)
    uploader = S3Uploader.new(options)
    form_tag(uploader.url, uploader.form_options) do
      uploader.fields.map do |name, value|
        hidden_field_tag(name, value)
      end.join.html_safe + capture(&block)
    end
  end

  class S3Uploader
    def initialize(options)
      @options = options.reverse_merge(
        id: "fileupload",
        aws_access_key_id: ENV["AWS_ACCESS_KEY_ID"],
        aws_secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"],
        bucket: ENV["AWS_S3_BUCKET"],
        acl: "public-read",
        expiration: 10.hours.from_now,
        max_file_size: 2.megabytes,
        as: "file"
      )
    end

    def form_options
      {
        id: @options[:id],
        method: "post",
        authenticity_token: false,
        multipart: true,
        data: {
          post: @options[:post],
          as: @options[:as]
        }
      }
    end

    def fields
      {
        :key => key,
        :acl => @options[:acl],
        :policy => policy,
        :signature => signature,
        "AWSAccessKeyId" => @options[:aws_access_key_id],
      }
    end

    def key
      @key ||= "uploads/#{SecureRandom.hex}/${filename}"
    end

    def url
      "https://#{@options[:bucket]}.s3.amazonaws.com/"
    end

    def policy
      Base64.encode64(policy_data.to_json).gsub("\n", "")
    end

    def policy_data
      {
        expiration: @options[:expiration],
        conditions: [
          ["starts-with", "$utf8", ""],
          ["starts-with", "$key", ""],
          ["content-length-range", 0, @options[:max_file_size]],
          {bucket: @options[:bucket]},
          {acl: @options[:acl]}
        ]
      }
    end

    def signature
      Base64.encode64(
        OpenSSL::HMAC.digest(
          OpenSSL::Digest::Digest.new('sha1'),
          @options[:aws_secret_access_key], policy
        )
      ).gsub("\n", "")
    end
  end
end

_form.html.erb: http://pastebin.com/Sqk8XK6U

还有create.js.erb(@image变量来自 Controller - 我认为它与发布 Controller 逻辑无关,因为它是一个javascript问题 ) http://pastebin.com/BBAGE5Me

所以我想在上传到 S3 之前调整图像大小以创建缩略图,这样我就不会浪费 S3 上的存储和客户端的带宽。有什么想法吗?

我已经尝试将相应的选项添加到 posts.js.coffee 脚本中: https://github.com/blueimp/jQuery-File-Upload/wiki/Options 但没有取得成功。

最佳答案

如果您之前检查过,您会发现其他类似的帖子。

似乎 add 回调会导致 process 函数被忽略,因此您必须在 add 回调中手动调用它。此外,您没有在代码中定义任何用于调整大小的选项...

我发布了一个类似的问题,并在一番尝试后自己解决了: Using jquery fileupload with coffeescript - resizing image when using add callback

关于jquery - 使用 JQuery 文件上传到亚马逊 S3 在客户端调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925700/

相关文章:

php - 将超链接添加到 Wordpress 的 Simplicity-Lite 特色框元素

ruby-on-rails - rails : Using greater than/less than with a where statement

ruby-on-rails - 将文件上传到 Ruby On Rails 4 中的特定文件夹

php - Laravel 认为 jQuery 总是 GET 请求方法

javascript - 更新页面加载时的价格字段

javascript - 如何在 Rails Turbolink 中正确使用 jQuery $().load(url)?

javascript - 从客户端计算机读取目录内容 - PHP

PHP 文件上传损坏的 JPEGS

php - 为什么使用 PHP 上传到 FTP 服务器的图像会损坏?

javascript - jQuery 没有在带有下拉列表的表单中选择正确的选项