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

2023-09-11 23:44:40 作者:老子就是王道

我已经看到一些例子在互联网这样的: 这 和 这个 ,但我跟随的 RailsCast情节#383上传到Amazon S3 ,并在视频的最后当然是使用JavaScript中,他提到了有关调整对客户端的图像。 问题是,我无法实现,如果我以他为榜样。我使用的是创业板的jQuery文件上传护栏

I already saw some examples at the internet like: this and this one, but I'm following the RailsCast Episode #383 Uploading to Amazon S3 and at the very end of the video he mentions about resize the image on the client-side using javascript, of course. The problem is, I can't implement if I follow his example. I'm using the gem jquery-fileupload-rails

修改:我发现我失踪的的 JQuery的,文件上传的例子来调整图像页面,但仍doesn't'work。 我需要的的application.js

EDIT: I noticed I was missing some JS required at the JQuery-fileupload example to resize image page, but still doesn't'work. My Requires on the 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 (路径:应用程序/佣工) http://pastebin.com/VxAbiUft

My upload_helper.rb ( path: 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 变量来自控制器 - 我不认为它的​​相关张贴控制器逻辑,因为它的一个JavaScript问题 ) http://pastebin.com/BBAGE5Me

And the create.js.erb ( the @image variable comes from the controller - I don't thinks its relevant to post the controller logic since its a javascript problem ) http://pastebin.com/BBAGE5Me

所以我要调整图像以创建上传到S3之前缩略图,所以我不会浪费我存储在S3和带宽给客户端。你知道吗?

So I want to resize the image to create thumbnails before uploads to S3, so I don't waste my storage on the S3 and bandwidth to the client. Any idea?

我已经尝试添加此相应的选项,以在 posts.js.coffee 脚本: https://github.com/blueimp/jQuery-File-Upload/wiki/Options 但没有成功达到了。

I already tried to add this respective options to the posts.js.coffee script: https://github.com/blueimp/jQuery-File-Upload/wiki/Options But no success was achieved.

推荐答案

如果你前检查周围,你会发现其他类似的职位。

If you checked around before, you would've found other similar posts.

看来,添加回调使得处理功能被忽略,所以你有附加回调中手动调用它。你也不必为调整在code定义的任何选项...

It seems that the add callback causes the process function to be ignored so you have to manually call it within the add callback. Also you don't have any options defined for resizing in your code...

我张贴了类似的问题,经过一番玩弄解决了它自己: Using jQuery的文件上传与CoffeeScript的 - 在使用添加回调调整图像

I posted a similar question and solved it myself after some playing around: Using jquery fileupload with coffeescript - resizing image when using add callback