In my rails app, I'm trying to upload files to AWS s3. I followed the this tutorial,http://ift.tt/1rlOGxv. I'm using the aws-sdk gem and JQuary File Upload Plugin to upload files. In my app i have a resource with two attributes: name, and file, and the file is a string. When the file is uploaded to the S3 bucket the URL is suppose to be saved into my database. But when i tried to upload a file in my application it saved this to my database: #\u003cActionDispatch::Http::UploadedFile:0x007fa212ad40b0\u003e, instead of saving the link to the file from where its stored in AWS S3.
This is the code in my controller pertaining to the file uploaded.:
def new
@s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: 201, acl: :public_read)
@resource = @person.resources.build
end
And the code in my form for the file upload is just a simple view with a file upload field.
The code of the javascript i'm using to upload the file is:
$(function() { $('.directUpload').find("input:file").each(function(i, elem) {
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.after(barContainer);
fileInput.fileupload({
fileInput: fileInput,
url: '<%= @s3_direct_post.url %>',
type: 'POST',
autoUpload: true,
formData: <%= @s3_direct_post.fields.to_json.html_safe %>,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
replaceFileInput: false,
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true);
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Uploading done");
// extract key and generate URL from response
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = '//<%= @s3_direct_post.url.host %>/' + key;
// create hidden field
var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
form.append(input);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed"); }});});});
If you could help me out that would be great! And if there is any other code that you need to look at just ask.
Aucun commentaire:
Enregistrer un commentaire