简体   繁体   English

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

[英]Resizing image at client-side using JQuery file upload to amazon S3

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. 我已经在互联网上看到了一些示例,例如: thisthis ,但是我正在跟踪RailsCast Episode#383 Uploading to Amazon S3 ,在视频的最后,他提到了使用javascript调整客户端图像大小的操作。 , 当然。 The problem is, I can't implement if I follow his example. 问题是,如果按照他的榜样,我将无法实施。 I'm using the gem jquery-fileupload-rails 我正在使用gem jquery-fileupload-rails

EDIT : I noticed I was missing some JS required at the JQuery-fileupload example to resize image page , but still doesn't'work. 编辑 :我注意到我在JQuery-fileupload示例中缺少一些JS 来调整图像页面的大小 ,但仍然无法正常工作。 My Requires on the application.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

My posts.js.coffee http://pastebin.com/9sm7UtsP 我的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)

My upload_helper.rb ( path: apps/helpers ) http://pastebin.com/VxAbiUft 我的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

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

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 create.js.erb@image变量来自控制器-我认为它与发布控制器逻辑无关,因为它是一个JavaScript问题) http://pastebin.com/BBAGE5Me

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. 因此,我想在上载到S3之前调整图像大小以创建缩略图,这样我就不会浪费我在S3上的存储空间和客户端的带宽。 Any idea? 任何想法?

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. 我已经尝试将各个选项添加到posts.js.coffee脚本中: https : //github.com/blueimp/jQuery-File-Upload/wiki/Options但没有成功。

If you checked around before, you would've found other similar posts. 如果您之前检查过,就会发现其他类似的帖子。

It seems that the add callback causes the process function to be ignored so you have to manually call it within the add callback. 似乎add回调导致process函数被忽略,因此您必须在add回调中手动调用它。 Also you don't have any options defined for resizing in your code... 另外,您没有定义任何用于调整代码大小的选项...

I posted a similar question and solved it myself after some playing around: Using jquery fileupload with coffeescript - resizing image when using add callback 我发布了一个类似的问题,并在玩了一会后自己解决了: 使用jquery fileupload与coffeescript-使用add回调时调整图像大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM