Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

use postMessage and display upload elements on host page

  • Loading branch information...
commit 9e2c2d00cc8f408f2525f22f77a9dcead42d9da3 1 parent ff44268
Nico authored
View
153 .idea/workspace.xml
@@ -22,10 +22,10 @@
</component>
<component name="FileEditorManager">
<leaf>
- <file leaf-file-name="uploads_controller.rb" pinned="false" current="true" current-in-tab="true">
+ <file leaf-file-name="uploads_controller.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/controllers/uploads_controller.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="15" column="9" selection-start="439" selection-end="439" vertical-scroll-proportion="0.5769231">
+ <state line="28" column="15" selection-start="720" selection-end="720" vertical-scroll-proportion="-14.038462">
<folding />
</state>
</provider>
@@ -34,16 +34,16 @@
<file leaf-file-name="uploads_helper.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/helpers/uploads_helper.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="29" column="9" selection-start="163" selection-end="820" vertical-scroll-proportion="0.0">
+ <state line="17" column="52" selection-start="841" selection-end="841" vertical-scroll-proportion="-10.961538">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="application_helper.rb" pinned="false" current="false" current-in-tab="false">
- <entry file="file://$PROJECT_DIR$/app/helpers/application_helper.rb">
+ <file leaf-file-name="amazon_s3.yml" pinned="false" current="false" current-in-tab="false">
+ <entry file="file://$PROJECT_DIR$/config/amazon_s3.yml">
<provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
+ <state line="10" column="13" selection-start="434" selection-end="445" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
@@ -52,7 +52,7 @@
<file leaf-file-name="upload.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/models/upload.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
+ <state line="1" column="0" selection-start="34" selection-end="34" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
@@ -61,16 +61,16 @@
<file leaf-file-name="20120216184202_create_uploads.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/db/migrate/20120216184202_create_uploads.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="3" column="16" selection-start="108" selection-end="169" vertical-scroll-proportion="0.0">
+ <state line="12" column="20" selection-start="231" selection-end="231" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="_uploader.html.haml" pinned="false" current="false" current-in-tab="false">
+ <file leaf-file-name="_uploader.html.haml" pinned="false" current="true" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/app/views/uploads/_uploader.html.haml">
<provider selected="true" editor-type-id="text-editor">
- <state line="74" column="4" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0">
+ <state line="12" column="25" selection-start="445" selection-end="445" vertical-scroll-proportion="0.39310345">
<folding />
</state>
</provider>
@@ -79,7 +79,7 @@
<file leaf-file-name="routes.rb" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/config/routes.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="4" column="4" selection-start="80" selection-end="80" vertical-scroll-proportion="0.0">
+ <state line="5" column="3" selection-start="100" selection-end="100" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
@@ -88,16 +88,16 @@
<file leaf-file-name="index.html.haml" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/views/uploads/index.html.haml">
<provider selected="true" editor-type-id="text-editor">
- <state line="3" column="74" selection-start="145" selection-end="145" vertical-scroll-proportion="0.0">
+ <state line="2" column="15" selection-start="58" selection-end="58" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
</file>
- <file leaf-file-name="Gemfile" pinned="false" current="false" current-in-tab="false">
- <entry file="file://$PROJECT_DIR$/Gemfile">
+ <file leaf-file-name="uploads.js.coffee" pinned="false" current="false" current-in-tab="false">
+ <entry file="file://$PROJECT_DIR$/app/assets/javascripts/uploads.js.coffee">
<provider selected="true" editor-type-id="text-editor">
- <state line="8" column="16" selection-start="158" selection-end="158" vertical-scroll-proportion="0.0">
+ <state line="14" column="23" selection-start="380" selection-end="380" vertical-scroll-proportion="-10.230769">
<folding />
</state>
</provider>
@@ -106,7 +106,7 @@
<file leaf-file-name="uploads.css.scss" pinned="false" current="false" current-in-tab="false">
<entry file="file://$PROJECT_DIR$/app/assets/stylesheets/uploads.css.scss">
<provider selected="true" editor-type-id="text-editor">
- <state line="28" column="1" selection-start="529" selection-end="529" vertical-scroll-proportion="0.0">
+ <state line="35" column="5" selection-start="566" selection-end="566" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
@@ -129,13 +129,16 @@
<option value="$PROJECT_DIR$/config/amazon_s3.yml" />
<option value="$PROJECT_DIR$/config/initializers/load_config.rb" />
<option value="$PROJECT_DIR$/app/views/layouts/application.html.haml" />
- <option value="$PROJECT_DIR$/app/assets/stylesheets/uploads.css.scss" />
<option value="$PROJECT_DIR$/Gemfile" />
+ <option value="$PROJECT_DIR$/app/models/upload.rb" />
+ <option value="$PROJECT_DIR$/db/migrate/20120216184202_create_uploads.rb" />
<option value="$PROJECT_DIR$/config/routes.rb" />
+ <option value="$PROJECT_DIR$/app/controllers/uploads_controller.rb" />
<option value="$PROJECT_DIR$/app/views/uploads/index.html.haml" />
<option value="$PROJECT_DIR$/app/helpers/uploads_helper.rb" />
+ <option value="$PROJECT_DIR$/app/assets/stylesheets/uploads.css.scss" />
+ <option value="$PROJECT_DIR$/app/assets/javascripts/uploads.js.coffee" />
<option value="$PROJECT_DIR$/app/views/uploads/_uploader.html.haml" />
- <option value="$PROJECT_DIR$/app/controllers/uploads_controller.rb" />
</list>
</option>
</component>
@@ -149,7 +152,7 @@
<component name="ProjectFrameBounds">
<option name="y" value="22" />
<option name="width" value="1280" />
- <option name="height" value="882" />
+ <option name="height" value="881" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="false">
<OptionsSetting value="true" id="Add" />
@@ -317,7 +320,51 @@
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
<PATH_ELEMENT>
- <option name="myItemId" value="helpers" />
+ <option name="myItemId" value="assets" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="stylesheets" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ </PATH>
+ <PATH>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="html5_s3_uploader" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="html5_s3_uploader" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="app" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="assets" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="javascripts" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ </PATH>
+ <PATH>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="html5_s3_uploader" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="html5_s3_uploader" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="app" />
+ <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
+ </PATH_ELEMENT>
+ <PATH_ELEMENT>
+ <option name="myItemId" value="assets" />
<option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" />
</PATH_ELEMENT>
</PATH>
@@ -656,18 +703,18 @@
<servers />
</component>
<component name="ToolWindowManager">
- <frame x="0" y="22" width="1280" height="882" extended-state="0" />
- <editor active="true" />
+ <frame x="0" y="22" width="1280" height="881" extended-state="0" />
+ <editor active="false" />
<layout>
<window_info id="Data Sources" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
<window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="true" content_ui="tabs" />
- <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.19967532" sideWeight="0.7968545" order="0" side_tool="false" content_ui="combo" />
+ <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.21672077" sideWeight="0.8425197" order="0" side_tool="false" content_ui="combo" />
<window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
<window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="true" content_ui="tabs" />
<window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="true" content_ui="tabs" />
- <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.20314547" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
+ <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.15748031" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
<window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="7" side_tool="false" content_ui="tabs" />
<window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
<window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
@@ -732,11 +779,6 @@
<breakpoint-manager />
</component>
<component name="editorHistoryManager">
- <entry file="file://$PROJECT_DIR$/config/initializers/wrap_parameters.rb">
- <provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
- </provider>
- </entry>
<entry file="file://$PROJECT_DIR$/config/initializers/backtrace_silencers.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
@@ -747,11 +789,6 @@
<state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0" />
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/config/amazon_s3.yml">
- <provider selected="true" editor-type-id="text-editor">
- <state line="7" column="10" selection-start="386" selection-end="386" vertical-scroll-proportion="0.0" />
- </provider>
- </entry>
<entry file="file://$PROJECT_DIR$/config/initializers/load_config.rb">
<provider selected="true" editor-type-id="text-editor">
<state line="3" column="9" selection-start="78" selection-end="78" vertical-scroll-proportion="0.0" />
@@ -769,63 +806,79 @@
<state line="8" column="16" selection-start="158" selection-end="158" vertical-scroll-proportion="0.0" />
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/assets/stylesheets/uploads.css.scss">
+ <entry file="file://$PROJECT_DIR$/app/helpers/application_helper.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="28" column="1" selection-start="529" selection-end="529" vertical-scroll-proportion="0.0" />
+ <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/config/routes.rb">
+ <entry file="file://$PROJECT_DIR$/config/amazon_s3.yml">
<provider selected="true" editor-type-id="text-editor">
- <state line="4" column="4" selection-start="80" selection-end="80" vertical-scroll-proportion="0.0">
+ <state line="10" column="13" selection-start="434" selection-end="445" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/db/migrate/20120216184202_create_uploads.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="3" column="16" selection-start="108" selection-end="169" vertical-scroll-proportion="0.0">
+ <state line="12" column="20" selection-start="231" selection-end="231" vertical-scroll-proportion="0.0">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/config/routes.rb">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="5" column="3" selection-start="100" selection-end="100" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
<entry file="file://$PROJECT_DIR$/app/models/upload.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
+ <state line="1" column="0" selection-start="34" selection-end="34" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/views/uploads/index.html.haml">
+ <entry file="file://$PROJECT_DIR$/app/helpers/uploads_helper.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="3" column="74" selection-start="145" selection-end="145" vertical-scroll-proportion="0.0">
+ <state line="17" column="52" selection-start="841" selection-end="841" vertical-scroll-proportion="-10.961538">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/helpers/application_helper.rb">
+ <entry file="file://$PROJECT_DIR$/app/assets/stylesheets/uploads.css.scss">
<provider selected="true" editor-type-id="text-editor">
- <state line="0" column="0" selection-start="0" selection-end="0" vertical-scroll-proportion="0.0">
+ <state line="35" column="5" selection-start="566" selection-end="566" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/helpers/uploads_helper.rb">
+ <entry file="file://$PROJECT_DIR$/app/controllers/uploads_controller.rb">
<provider selected="true" editor-type-id="text-editor">
- <state line="29" column="9" selection-start="163" selection-end="820" vertical-scroll-proportion="0.0">
+ <state line="28" column="15" selection-start="720" selection-end="720" vertical-scroll-proportion="-14.038462">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/views/uploads/_uploader.html.haml">
+ <entry file="file://$PROJECT_DIR$/app/views/uploads/index.html.haml">
<provider selected="true" editor-type-id="text-editor">
- <state line="74" column="4" selection-start="1836" selection-end="1836" vertical-scroll-proportion="0.0">
+ <state line="2" column="15" selection-start="58" selection-end="58" vertical-scroll-proportion="0.0">
<folding />
</state>
</provider>
</entry>
- <entry file="file://$PROJECT_DIR$/app/controllers/uploads_controller.rb">
+ <entry file="file://$PROJECT_DIR$/app/assets/javascripts/uploads.js.coffee">
+ <provider selected="true" editor-type-id="text-editor">
+ <state line="14" column="23" selection-start="380" selection-end="380" vertical-scroll-proportion="-10.230769">
+ <folding />
+ </state>
+ </provider>
+ </entry>
+ <entry file="file://$PROJECT_DIR$/app/views/uploads/_uploader.html.haml">
<provider selected="true" editor-type-id="text-editor">
- <state line="15" column="9" selection-start="439" selection-end="439" vertical-scroll-proportion="0.5769231">
+ <state line="12" column="25" selection-start="445" selection-end="445" vertical-scroll-proportion="0.39310345">
<folding />
</state>
</provider>
View
63 app/assets/javascripts/uploads.js.coffee
@@ -1,3 +1,60 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
+jQuery ->
+
+ xhrUploadProgressSupported = () ->
+ xhr = new XMLHttpRequest()
+ xhr && ('upload' of xhr) && ('onprogress' of xhr.upload)
+
+ randomString = (length) ->
+ chars = '0123456789abcdefghiklmnopqrstuvwxyz'
+ sRnd = ''
+ for i in [0...length]
+ randomPoz = Math.floor Math.random() * chars.length
+ sRnd += chars.substring randomPoz,randomPoz+1
+
+ sRnd
+
+ # Can only track progress if size property is present on files.
+ progressSupported = xhrUploadProgressSupported()
+
+ $('#uploading_files').on 'click', '.uploading_file .remove_link', (e) ->
+ uuid = $(this).parent().attr('id')
+ $(this).parent().remove()
+ $('#uploader iframe')[0].contentWindow.postMessage({ eventType: 'abort upload', uuid: uuid }, 'http://do2-media.s3.amazonaws.com');
+
+ window.addEventListener "message", (event) ->
+ if event.origin != "http://do2-media.s3.amazonaws.com"
+ return
+
+ eventType = event.data.eventType;
+ delete event.data.eventType;
+
+ data = event.data
+
+ switch eventType
+
+ when 'upload done'
+
+ $(".uploading_file##{data.uuid}").remove()
+
+ $.ajax $('#uploader iframe').data('create-resource-url'),
+ type: 'POST',
+ data: data
+
+
+ when 'add upload'
+
+ if progressSupported
+ uploadPercent = "<br/><progress value='0' max='100' class='upload_progress_bar'>0</progress> <span class='upload_percentage'>0</span> %";
+ $('#uploading_files').append("<p class='uploading_file'>#{data.file_name + uploadPercent} <a href='#' class='remove_link'>X<a/></p>");
+ else
+ $('#uploading_files').append("<p class='uploading_file'>#{data.file_name}<br/><img src='img/uploading.gif'/></p>");
+
+ $('.uploading_file').last().attr 'id', data.uuid
+
+
+ when 'upload progress'
+
+ if progressSupported
+ $(".uploading_file##{data.uuid}").find('.upload_percentage').html(data.progress)
+ $(".uploading_file##{data.uuid}").find('.upload_progress_bar').val(data.progress)
+
View
33 app/assets/stylesheets/uploads.css.scss
@@ -26,4 +26,37 @@ h1{
min-height: 300px;
padding: 10px;
border-radius: 7px;
+}
+
+
+progress{
+ width: 200px;
+}
+
+#drag_text{
+ position: absolute;
+ z-index: 0;
+ top:0;
+ left:0;
+ width: 500px;
+ padding-top:100px;
+ text-align: center;
+ font-size: 2em;
+ font-weight: bold;
+ color: #ddd;
+ font-style:italic;
+}
+
+#uploading_files, #file_upload{
+ position: relative;
+ z-index: 1;
+}
+
+#drag_remark{
+ font-size: 0.5em;
+}
+
+.remove_link{
+ color: red;
+ text-decoration: none;
}
View
71 app/controllers/uploads_controller.rb
@@ -2,72 +2,23 @@
class UploadsController < ApplicationController
def index
-
- #uploader_html = render_to_string( partial: 'uploads/uploader',
- # locals: { after_upload_url: url_for(controller: controller_name, action: create) } )
- #ensure_s3_connection!
- #AWS::S3::S3Object.store(
- # 'uploader/uploader.html',
- # uploader_html,
- # S3_CONFIG['bucket_name'],
- # :access => :public_read
- #)
-
-
- # raise s3_signature(path: folder)
-
- folder = 'uploaded_files'
- @frame_params = (["key=#{s3_key(folder)}",
- "AWSAccessKeyId=#{S3_CONFIG['access_key_id']}",
- "policy=#{s3_policy(path: folder)}",
- "signature=#{s3_signature(path: folder)}"].join('&')).gsub('=', '%3D')
- end
-
-
- def s3_bucket_url
- "http://#{S3_CONFIG['bucket_name']}.s3.amazonaws.com/"
- end
-
-
- def s3_key path
- "#{path}/${filename}"
- end
-
-
- def s3_policy options = {}
- options[:content_type] ||= ''
- options[:acl] ||= 'public-read'
- options[:max_file_size] ||= 20.megabyte
- options[:path] ||= ''
-
- Base64.encode64(
- "{'expiration': '#{10.hours.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')}',
- 'conditions': [
- {'bucket': '#{S3_CONFIG['bucket_name']}'},
- ['starts-with', '$key', '#{options[:path]}'],
- {'acl': '#{options[:acl]}'},
- {'success_action_status': '201'},
- ['content-length-range', 0, #{options[:max_file_size]}],
- ['starts-with', '#{options[:content_type]}', '']
- ]
- }").gsub(/\n|\r/, '')
- end
-
-
- def s3_signature options = {}
- Base64.encode64(
- OpenSSL::HMAC.digest(
- OpenSSL::Digest::Digest.new('sha1'),
- S3_CONFIG['secret_access_key'], s3_policy(options))).gsub("\n","")
+ uploader_html = render_to_string( partial: 'uploads/uploader' )
+ ensure_s3_connection!
+ AWS::S3::S3Object.store(
+ 'uploader/uploader.html',
+ uploader_html,
+ S3_CONFIG['bucket_name'],
+ :access => :public_read
+ )
end
def create
- @upload = Upload.new(params[:upload])
+ @upload = Upload.new(params[:upload] || params.delete_if{ |p| !Upload.attribute_names.include?(p) })
if @upload.save
- render text: 'Upload created!', status: 201
+ render nothing: true
+ #render js: "$('#uploading_files').html('Test')", status: 201
end
-
headers['Access-Control-Allow-Origin'] = 'http://do2-media.s3.amazonaws.com'
headers['Access-Control-Allow-Methods'] = '*'
end
View
26 app/helpers/uploads_helper.rb
@@ -1,5 +1,26 @@
module UploadsHelper
+
+ def s3_uploader options = {}
+ options[:uploader_path] ||= 'uploader/uploader.html'
+ options[:uploaded_files_path] ||= "#{controller_name}/:uuid"
+ options[:create_resource_url] ||= url_for(only_path: false)
+ options[:resource_name] ||= controller_name.singularize
+
+ upload_params = { key: s3_key(options[:uploaded_files_path]),
+ AWSAccessKeyId: S3_CONFIG['access_key_id'],
+ _policy: s3_policy(path: options[:uploaded_files_path]),
+ _signature: s3_signature(path: options[:uploaded_files_path]) }.to_query
+
+ content_tag :iframe, '',
+ src: "http://#{S3_CONFIG['bucket_name']}.s3.amazonaws.com/#{options[:uploader_path]}?#{upload_params}",
+ frameborder: 0,
+ height: options[:iframe_height] || 60,
+ width: options[:iframe_width] || 500,
+ data: { create_resource_url: options[:create_resource_url] }
+ end
+
+
def s3_bucket_url
"http://#{S3_CONFIG['bucket_name']}.s3.amazonaws.com/"
end
@@ -20,11 +41,11 @@ def s3_policy options = {}
"{'expiration': '#{10.hours.from_now.utc.strftime('%Y-%m-%dT%H:%M:%S.000Z')}',
'conditions': [
{'bucket': '#{S3_CONFIG['bucket_name']}'},
- ['starts-with', '$key', '#{options[:path]}'],
+ ['starts-with', '$key', ''],
{'acl': '#{options[:acl]}'},
{'success_action_status': '201'},
['content-length-range', 0, #{options[:max_file_size]}],
- ['starts-with', '#{options[:content_type]}', '']
+ ['starts-with','$Content-Type','']
]
}").gsub(/\n|\r/, '')
end
@@ -37,4 +58,5 @@ def s3_signature options = {}
S3_CONFIG['secret_access_key'], s3_policy(options))).gsub("\n","")
end
+
end
View
2  app/models/upload.rb
@@ -1,2 +1,4 @@
class Upload < ActiveRecord::Base
+
+
end
View
103 app/views/uploads/_uploader.html.haml
@@ -19,7 +19,6 @@
color:#666666;
margin:0;
padding:0;
- height: 300px;
}
progress{
@@ -31,7 +30,7 @@
z-index: 0;
top:0;
left:0;
- width: 500px;
+
padding-top:100px;
text-align: center;
font-size: 2em;
@@ -75,81 +74,89 @@
%input{:type => :file, :name => 'file', multiple: ''}
- #uploading_files
-
:javascript
$(function() {
- //alert(location.href.replace(/%2F/g, '/').replace(/%3D/g, '='))
- var params = location.href.replace(/%3D/g, '=').split('?')[1].split('&');
+
+ var params = unescape(location.href).split('?')[1].split('&');
+
+ var createResourceUrl;
+
+ var jqXHR = new Array();
+
+ //// Can only track progress if size property is present on files.
+ //var progressSupported = xhrUploadProgressSupported();
for (x in params){
- $('#file_upload input[name=' + params[x].split('=')[0] + ']').val(params[x].substring(params[x].search('=')+1));
+ key = params[x].split('=')[0]
+ val = params[x].substring(params[x].search('=')+1);
+ $('#file_upload input[name=' + key.replace(/^_/,'') + ']').val(val);
}
+
// Opera doesn't handle multiple files properly so use single file selection there
if (navigator.appName == 'Opera') {
$('#file_upload').find('input:file').each(function () {
$(this).removeAttr('multiple')
- // Fix for Opera, which ignores just removing the multiple attribute:
- .replaceWith($(this).clone(true));
+ // Fix for Opera, which ignores just removing the multiple attribute:
+ .replaceWith($(this).clone(true));
});
}
- function xhrUploadProgressSupported(){
- var xhr = new XMLHttpRequest();
- return !! (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
+ function randomString(length) {
+ var chars = 'abcdefghiklmnopqrstuvwxyz';
+ var sRnd = '';
+ for (var i=0; i<length; i++){
+ var randomPoz = Math.floor(Math.random() * chars.length);
+ sRnd += chars.substring(randomPoz,randomPoz+1);
+ }
+ return sRnd;
}
+ window.addEventListener("message", function (e) {
+ if (e.origin !== "http://localhost:3000")
+ return;
+ jqXHR[e.data.uuid].abort();
+ });
+
$('#file_upload').fileupload({
dropZone: $(document.body),
url: "#{s3_bucket_url}",
formData: function (form) {
- return form.serializeArray();
+ data = form.serializeArray();
+ if ('type' in this.files[0])
+ data.push({ name: 'Content-Type', value: this.files[0].type })
+ data[0].value = data[0].value.replace(':uuid', this.context)
+ return data;
},
fail: function(e, data) {
//
},
add: function (e, data) {
- // Can only track progress if size property is present on files.
-
- progressSupported = xhrUploadProgressSupported();
- $.each(data.files, function (index, file) {
- if( progressSupported ){
- var uploadPercent = "<br/><progress value='0' max='100' class='upload_progress_bar'>0</progress> <span class='upload_percentage'>0</span>" + '%';
- $('#uploading_files').append("<p class='uploading_file'>" + file.name + uploadPercent + " <a href='#' class='remove_link'>X<a/></p>");
- } else
- $('#uploading_files').append("<p class='uploading_file'>" + file.name + "<br/><img src='img/uploading.gif'/></p>");
- });
-
- data.context = $('.uploading_file').last();
- data.jqXHR = data.submit();
-
- $('.uploading_file .remove_link').last().click(function (e) {
- data.jqXHR.abort();
- data.context.hide()
- });
+ postData = { eventType: 'add upload' }
+ postData.uuidInKey = $('#file_upload input[name=key]').val().search(':uuid') != -1;
+ postData.file_name = data.files[0].name
+ postData.uuid = randomString(20);
+
+ window.parent.postMessage(postData, 'http://localhost:3000');
+
+ data.context = postData.uuid;
+ jqXHR[postData.uuid] = data.submit();
+
},
progress: function (e, data) {
- if( xhrUploadProgressSupported() ){
- var progress = parseInt(data.loaded / data.total * 100, 10);
- data.context.find('.upload_percentage').html(progress);
- data.context.find('.upload_progress_bar').val(progress);
- }
+ window.parent.postMessage({ eventType: 'upload progress',
+ uuid: data.context,
+ progress: parseInt(data.loaded / data.total * 100, 10) },
+ 'http://localhost:3000');
},
done: function (e, data) {
- data.context.hide();
var file = data.files[0];
- //var params = { file_name: file.name }
- //if ('size' in file)
- // params.file_size = file.size;
- //if ('type' in file)
- // params.file_type = file.type;
- //$.ajax('#{after_upload_url}',
- // { type: 'POST',
- // data: "upload[file_name]=" + encodeURIComponent(file.name) } )
+ var postData = { eventType: 'upload done', uuid: data.context };
+ postData.file_name = file.name;
+ postData.s3_key = $('#file_upload input[name=key]').val().replace('/${filename}', '').replace(':uuid', data.context);
+ if( 'size' in file ) postData.file_size = file.size;
+ if( 'type' in file ) postData.file_type = file.type;
+ window.parent.postMessage(postData, 'http://localhost:3000');
},
- stop: function(e){
- $('.uploading_file').remove()
- }
});
});
View
8 app/views/uploads/index.html.haml
@@ -1,7 +1,5 @@
%h1 jQuery S3 File Uploader Demo
#uploader
- -##{SecureRandom.hex(10)}
- %iframe{ src: "http://do2-media.s3.amazonaws.com/uploader/uploader.html?#{@frame_params}",
- frameborder: 0,
- height: 300,
- width: 500 }
+ = s3_uploader create_resource_url: uploads_url
+
+ #uploading_files
View
1  config/routes.rb
@@ -3,5 +3,6 @@
root :to => 'uploads#index'
resources :uploads
+ #match '/uploads' => 'uploads#options', :constraints => {:method => 'OPTIONS'}
end
View
1  db/migrate/20120216184202_create_uploads.rb
@@ -4,6 +4,7 @@ def change
t.string :file_name
t.string :file_type
t.string :file_size
+ t.string :s3_key
t.timestamps
end
View
1  db/schema.rb
@@ -17,6 +17,7 @@
t.string "file_name"
t.string "file_type"
t.string "file_size"
+ t.string "s3_key"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
Please sign in to comment.
Something went wrong with that request. Please try again.