waynehoover / s3_direct_upload Goto Github PK
View Code? Open in Web Editor NEWDirect Upload to Amazon S3 With CORS
License: MIT License
Direct Upload to Amazon S3 With CORS
License: MIT License
Does this work with IE 8/9/10?
complete and failed hooks worked except for start. I double-checked the spellings and to no avail.
I am currently implementing a form to create and edit products. Apart from a title and price, the user should be able to upload a picture. As far as I see the picture upload have to be wrapped into its own form, am I right? Do you think it would be possible to refactor the (really great!) s3_direct_upload plugin so that it doesn't require a form but operates on a div instead (as discussed in blueimp/jQuery-File-Upload#76 , for example)? Or am I missing something?
As per #46
Amazon returns a Forbidden 403 on posts following an update of the jquery-rails gem from 2.1.4 to 2.20, which upgrades JQuery from 1.8.3 to 1.9. Upon analyzing the request headers, it looks like the file data is not being correctly passed in 1.9.
Is it possible to implement a PUT method as the post one.
My uploaded file_url is a part of a document containing some informations as "name", "description" etc.
I would like to be able to update the file_url for a specific document.
So I tried to use the code in my form :
<%= s3_uploader_form post: edit_medium_path(@Medium), as: "medium[file_url]", id: "myS3Uploader" do %>
<%= file_field_tag :file, multiple: false %>
<% end %>
But, it doesn't work cos update method need PUT not POST.
I tried to use the Create method passing the id with the data: option but I don't really understand how to use it and if it is possible.
Thanks for your help.
Stephane
I'd like to integrate some of the file preview functionality from jquery file upload.
Would that be useful as part of this project? I'm happy to provide a pull request, just need some guidance to find the right places to hook it up.
I am getting this javascript error in the browser when I am trying to upload a file.
Uncaught Error: Syntax error, unrecognized expression: <div class='upload' id='file-jvrw6xn741i9hpvi'>
june-12-chromatic_baba__95-nocal-1920x1200.jpg
<div class='progress'>
<div class='bar' style='width: 0%'></div>
</div>
</div>
Am I missing something?
Hi Wayne,
Sorry to pollute your issue tracker with this but it is more of a question. I also posted it over the comment thread for the RailsCasts where I found the link to this gem.
Hopefully you may be able to shed some light, otherwise please disregard and delete.
Again sorry for polluting
Cheers
Luke
http://railscasts.com/episodes/383-uploading-to-amazon-s3?view=comments
File chunking.
maxChunkSize: 1000000
I am finding that this directive is working for me. However S3 is not merging the file back together at their end.
I am only getting the last chunked bit of the file appearing in the folder.
I have found this
http://aws.amazon.com/articles/1109?_encoding=UTF8&jiveRedirect=1#14
But am a little unsure what to make of it. Was wondering if anyone else has come across this issue as it is pretty cool feature jquery upload. I am uploading video files and so being able to do it in batches means that their is less chance of file failure.
Hope someone can shed some light.
Kind regards,
Luke
Need the ability to change the filename before it gets uploaded to S3.
For instance, the original filename is "picture.jpg" and need to rename it to "2012_01_31_picture.jpg".
I'm testing this with IE and although the upload gets done to S3, the Done callback never seems to execute. Is this a known issue ?
I'm trying to implement this functionality in my application.
What I've got:
Request URL:http://s3.amazonaws.com/application/
Request Method:OPTIONS
Status Code:403 Forbidden
Accept:/
Accept-Encoding:gzip,deflate,sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, origin, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:s3.amazonaws.com
Origin:http://application.dev
Referer:http://application.dev/lectures/51a3731d6206ad2f35000001
CORS setup:
{:id=>"application.dev", :allowed_methods=>["HEAD", "PUT", "POST", "GET", "DELETE"], :allowed_origins=>["htpp://application.dev"], :allowed_headers=>["*"], :max_age_seconds=>3600}
So It doesn't work but when I add button to form like this
= s3_uploader_form callback_url: lecture_url, callback_method: :put ,callback_param: "lecture[video]", id: "myS3Uploader", key: "uploads/lectures/#{SecureRandom.hex}/${filename}", ssl: false do
= hidden_field_tag "Content-Type", ""
= file_field_tag :file
%button.submit-target Submit
and file path is chosen (firefox) and click on button
it redirects me to my bucket on s3 with xml
<PostResponse><Location>http://s3.amazonaws.com/application/uploads%2Flectures%2Fc582a31ffd7e4a419bdc6ce3ade99390%2Fsmall.mp4</Location><Bucket>application</Bucket><Key>uploads/lectures/c582a31ffd7e4a419bdc6ce3ade99390/small.mp4</Key><ETag>"a3ac7ddabb263c2d00b73e8177d15c8ad"</ETag></PostResponse>
and file is uploaded to AWS.
in js.coffee
$("#myS3Uploader").S3Uploader()
when i add option to js:
$("#myS3Uploader").S3Uploader()
click_submit_target: $('.submit-target')
it gets 403 forbidden like original request.
What is going on?
It looks like OPTIONS is not allowed but it can send to bucket file from form with button without js.
So I can send file directly to AWS from form but I cannot with jQuery request.
This is the fail
function that is used right now when an upload doesn't complete :
fail: (e, data) ->
alert("#{data.files[0].name} failed to upload.")
console.log("Upload failed:")
console.log(data)
We should be able to customize this part. I'm not sure what is the best way to to this. Should we remove the actual fail code and just trigger a failed event. Or should this be the default behaviour that can be optionally be overriden by an initialization parameter ?
Hi,
love this; we deal with large files a lot; is there any way to make the progress bars interruptible? i.e. they would have a link on them to stop the upload.
Not sure how difficult that would be. Any suggestions welcome.
thnx
Any ideas why this would be happening?
AccessDenied
Invalid according to Policy: Policy Condition failed: ["starts-with", "$Content-Type", ""]
D7C6C1FE8775221F
5qRPVAAM/6iZF0w8vfOlrm67FXoCiDZyDeZklt/lL2ndLb4+/Cry4JclqN/Zsw7L
I'm having a weird character encoding issue and I have been banging my head on the wall for most of the afternoon about this.
If I try to upload an image named léo.jpg, it will work fine with Firefox and but fails to render the uploaded image in Chrome. The problem seems to be that Chrome uses precomposed characters for the encoding the filename while Firefox uses combining characters.
At some point (not sure where yet), the filename gets converted to combining characters and that breaks Chrome rendering. I just tried the Railscasts demo to make sure it wasn't just my code and the same happens. Chrome uploads the image to S3 but fails to render it since it uses a different encoding to query S3 for the file (both are legal UTF-8).
I'm not sure if I'm being clear but can you confirm you get the same behaviour ?
It seems that AWS S3 API has changed endpoint url to:
https://{bucket}.s3.amazonaws.com/
instead of
https://{region}.amazonaws.com/{bucket}/
It would be nice if we were able to overwrite the API url on the configuration.
Great job!
Hi folks. First off, cheers for putting the work into this gem. Please forgive this "issue" which is more of a question, but one that I haven't seen answered anywhere. My experience up until now has been with Paperclip, and the clear object/s3 upload relationship that exists:
photo.rb
class Photo < ActiveRecord::Base
has_attached_file :image
photo.create(:image => params[:file]) # => creates a photo object, uploads the image to s3, and sets metadata
photo.image # => returns image object
photo.image = nil # => deletes the image on s3
photo.destroy # deletes the photo object and deletes the image on s3
I'm wondering how you guys are handling callbacks, resizing, and such with direct upload methods like this gem. Also deleting s3 assets if the record is deleted.
Enlightenment appreciated.
hi, i'm probably missing something very stupid, but I get this js error on page load:
Uncaught TypeError: Object function (b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])} has no method 'extend'
jquery.ui.widget.js:236
any input much appreciated
Hi,
Sorry I'm a bit new in ROR world, so I probably miss something but, when I try to display the S3 Form I've a routing errors.
Form code :
<%= s3_uploader_form post: medium_url, as: "Medium[url]", id: "myS3Uploader" do %>
<%= file_field_tag :file, multiple: true %>
<% end %>
Error :
No route matches {:action=>"show", :controller=>"media"}
I don't really understand cos, the previous code is in my _form for a new medium not in the show.html.erb
I tried to add that kind of routes but it doesn't change anything :
post 'medium_url', to: 'medium#new', as: 'medium_url'
So, I want to display the S3 Upload Form in my media/new page, uploading the file on my S3 and recording the url in my Medium model (url field).
I miss understand something :(
Thanks for your help
This may be something that I can fix on the S3 side of things that I just currently don't know about, however the URL that this gem is requesting is https://s3.amazonaws.com/bucket/ is there no way to use https://bucket.s3.amazonaws.com ? That is what I have used with Carrierwave and every other gem out there using S3 as a storage system. Is there a setting in S3 I need to change, or could this become an option in the config?
Edit: This was a foolish typo error. Ignore this issue.
I dropped my S3DirectUpload.config in an initializer, however this doesn't load when running
rake s3_direct_upload:clean_remote_uploads
saying that Missing required arguments: aws_access_key_id, aws_secret_access_key
Seems the rake task needs :environment.
task :clean_remote_uploads => :environment do
I forked and made the change locally without success, any thoughts? I think my local version of the gem may not have been loading, as that should be the fix (I think).
Hi,
May I know where to pass the options for the bucket region? Currently my bucket is located in the asia pacific region and requires a url like https://s3-ap-southeast-1.amazonaws.com but the upload is currently pointing to https://s3.amazonaws.com as the default. Am I able to set it in the initialiser file:
S3DirectUpload.config do |c|
c.access_key_id = CONFIG[:aws_access_key_id] # your access key id
c.secret_access_key = CONFIG[:aws_secret_access_key] # your secret access key
c.bucket = CONFIG[:aws_s3_bucket] # your bucket name
c.region = CONFIG[:aws_s3_region] # Is this possible?
end
Thanks!
This might not be the place to bring this up, as it relates more to jquery upload, or more specifically where it interfaces with S3, but....
Is it possible to have the progress bar display more info - speed, amount uploaded already, estimated time. Is there any more data on whatever object handles the upload available for display?
Just tried this gem for the first time and it doesn't work out of the box. I'm getting a bad request error back from amazon with the following error:
<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>MaxPostPreDataLengthExceeded</Code><Message>Your POST request fields preceeding the upload file was too large.</Message><MaxPostPreDataLengthBytes>20480</MaxPostPreDataLengthBytes><RequestId>9D23B2C9005839DC</RequestId><HostId>tzLn4c+k9tWoF69pDLBmwDdkHHrHuMR/yNYXi0oeIjaqr72HUGUnPsvwjqnIuLbk</HostId></Error>
I've run into an issue where uploads with the same file name are over writing each other, because the same server-generated path is being used for every file. This is particularly problematic for mobile uploads, where every photo from your camera roll gets named image.jpg by iOS.
A unique path should be generated for every upload:
key: "uploads/${JavaScript generated path}/${filename}"
Could we use the existing uniqueid js var? I'm currently looking into if it could be appended when generating the data path in the formData method.
I'd like to add Content-Disposition: attachment
to all uploaded files so that if the download link is visited, browsers are forced to download the file.
For example if you hit the download URL for an mp3 without Content-Disposition: attachment
, Chrome will just stream the mp3 in the browser. But if you set Content-Disposition: attachment
, Chrome will download the file.
Thanks!
Has anyone successfully implemented the ability to restrict certain file types from being uploaded? I'm looking to prevent my users from uploading PDF's.
Hi,
I don't use the Assets Pipeline in my projet it was a bit hard for this first project to use it with the theme I use (many js and css), so, is there a way to use this gem with no assets pipeline ?
Thanks
Trying to use:
S3DirectUpload.config do |c|
c.url = "https://test.bucket.com"
end
Results in:
NoMethodError: undefined method `url=' for #<S3DirectUpload::Config:0x0000010352dd80>
~/Code/app/config/initializers/s3_direct_upload.rb:2:in `block in <top (required)>'
~/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/s3_direct_upload-0.1.2/lib/s3_direct_upload/config_aws.rb:14:in `config'
Gemfile said I had the latest version, had to fix by adding the git repo to my gemfile.
gem 's3_direct_upload', :git => "https://github.com/waynehoover/s3_direct_upload.git"
I was successful at using carrierwave_direct and decided to switch to jquery file upload.
The app throws these errors as I try to upload a test image file to AWS. Do you know what possibly causes the issues.
+++ OPTIONS https://test-bucket.s3.amazonaws.com/ 403 (Forbidden)
send jquery.js:8417
jQuery.extend.ajax jquery.js:7969
send jquery.fileupload.js:652
$.widget._onSend jquery.fileupload.js:714
newData.submit jquery.fileupload.js:753
$uploadForm.fileupload.add s3_direct_upload.js:31
$.Widget._trigger jquery.ui.widget.js:278
(anonymous function) jquery.fileupload.js:756
jQuery.extend.each jquery.js:612
$.widget._onAdd jquery.fileupload.js:746
(anonymous function) jquery.fileupload.js:883
fire jquery.js:975
self.add jquery.js:1019
promise.always jquery.js:1116
$.widget._onChange jquery.fileupload.js:877
jQuery.event.dispatch jquery.js:3064
elemData.handle.eventHandle
+++ XMLHttpRequest cannot load https://test-bucket.s3.amazonaws.com/. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
This is a minor annoyance but when I do an upload and take look at the XML response from S3 in Firebug, I have this error :
XML Parsing Error: no element found Location: moz-nullprincipal:{075407ee-9c00-d443-a2f1-6721c3327352}
I also tried with the Railscasts source example and get the same error. But the upload works fine with all the callbacks. The only problem seems to be that the progress bar never get to 100%. I don't see this error message in Chrome and the progress bar works fine all the way to 100%.
Can you confirm Firebug gives you the same error? I searched for an explanation and tried different things but couldn't get rid of it.
I followed the documentation and it resulted in the error below. Once c.url = ""
was removed from the s3_direct_upload.rb
file, the problem fixes.
14:39:13 web.1 | /home/9dosl/Project-X/config/initializers/s3_direct_upload.rb:8:in `block in <top (required)>': undefined method `url=' for #<S3DirectUpload::Config:0x007f9126c88fc0> (NoMethodError)
14:39:13 web.1 | from /Users/hg/.rvm/gems/ruby-1.9.3-p392-railsexpress@px/gems/s3_direct_upload-0.1.2/lib/s3_direct_upload/config_aws.rb:14:in `config'
14:39:13 web.1 | from /home/9dosl/Project-X/config/initializers/s3_direct_upload.rb:3:in `<top (required)>'
Hi,
Is there a way to resize images to a specific size before uploading to S3 ?
Thanks
Hi all, sorry for asking a question in the issues section. Is there any way to use this gem for single uploads only?
I have this gem working great with multiple uploads, but on some pages I want to limit it to single uploads if possible (for example, uploading user avatars)
Many thanks!
Hello,
I am working on an issue in IE10. The uploads always seem to fail, the error thrown is: Error: access denied. This is only happening for IE10, is there something about the CORS file that could be off?
Thanks,
Cory
Hi,
I am having a hard time to try to upload directly to S3 using JS. I want to be compatible with IE < 10 also and then have to forget about XHR requests...
I wonder if your plugin handle iFrame POST request or not ?
Thanks
Since the most recent release added this designation, I've been seeing filenames like this end up in my uploads:
It seems like in some cases, the browser is not correctly replacing the timestamp and unique_id variables on upload. Is there any way to troubleshoot this issue?
The file_path built in build_content_object is inconsitent between browsers like chrome and IE. In IE the bucket name and filename is not included but in chrome they are. Also in chrome the path is escaped, but not in IE:
Chrome:
/bucket/escaped_path/escaped_filename
IE:
unescaped_path
This causes issues later when working with the path serverside.
I'm getting this error in the Chrome Inspector when selecting files to upload:
Uncaught Error: Syntax error, unrecognized expression: <div class="upload">
Screen Shot 2013-01-21 at 2.41.58 PM.png
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
Any ideas what is happening? Here is my view:
<%= s3_uploader_form post: new_asset_url, as: "asset[asset]", id: "myS3Uploader" do %>
<%= file_field_tag :asset, multiple: true %>
<% end %>
Routes:
post "/assets/new" => "assets#create", :as => :new_asset
//= require jquery
//= require best_in_place
//= require jquery_ujs
//= require jquery.ui.all
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require s3_direct_upload
Hi,
I change my project to activate Assets and it works fine (css, js etc.)
But, when I try to post my form nothing happens !
The S3 form seems to be ok.
My template need JQuery 1.8.3 so I include it in my application.html.erb, is it a problem ? I don't know which version Rails use, but is it possible there is a conflict ?
Thanks for your help !
Why am I running into:
OPTIONS https://.amazonaws.com/bucketname/ Resource failed to load
Thanks!
There is no callback triggered for each individual file.
Nulogy has implemented a solution https://github.com/nulogy/s3_direct_upload
$uploadForm.trigger("s3_upload_complete", [content])
I'm probably missing something obvious but i'm getting this error when attempting to load the page.
It occurs on Line 17.
14:
I'd like to limit my form to upload images only. I've written some javascript to check file formats, but I don't feel this is secure enough. There is no policy setting on S3 to have it deny unapproved file formats, but I've read that I can include an input in my POST form that will specify the file formats Amazon S3 should expect on POST. I'm not yet sure how this work, but I'm hoping it will result in not submitting files other than image types.
Here is the input I would like to include. Will this work as I expect? And how can I include it in the form?
Thanks & great gem!!!
Any ideas why I'm getting this 403 error?
AccessDenied
Invalid according to Policy: Extra input fields: content-type
It seems that the '$Content-type' part of the policy is ending up 'content-type', and S3 doesn't seem to like that very much.
I noticed during a rudimentary test today that the max_file_size param correctly limits uploads with s3, but an error is only thrown when s3 reaches its policy limit. Oversized files should not be addable in the first place, or should give an immediate error and be removed from the queue.
Any idea whey I consistently get "Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin." error on s3?
I've tried several different projects to get this working including the Ryan Bates Screencast and this one: http://pjambet.github.com/blog/direct-upload-to-s3/. Always the same result. My app works fine with a standard carrierwave direct upload (so I know my bucket and credentials are ok). But once I introduce ajax into the mix 100% failure with the error above.
I saw this bug reported: http://code.google.com/p/chromium/issues/detail?id=67743 so I switched from chrome to safari and then firefox. Same result. I deleted my bucket and recreated and reset up CORS. I tried CORS with http://0.0.0.0:3000, http://localhost:3000, * for the allowed origin.
Any ideas? Driving me nuts.
A malicious user could alter the key field in the form to upload to an unexpected location within your bucket, even replacing an existing file.
my callback_url seems to work great in development mode, but when deploying nothing gets triggered. Any reason why this may happen?
Hello,
Great gem you have over here, very helpful.
When I upload a file like chrome & canary + something.jpg
, content.url returns the exact same thing, but the actual S3 link is chrome+%26+canary+%2B+something.jpg
. If I try and visit what content.url returned, I get an access denied error from S3, but really that's because no file exists there.
I believe this has to do with escaping/encoding ampersands, pluses, and spaces.
Any ideas how to solve this? Thanks!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.