Skip to content
This repository

ajax image upload #1903

Merged
merged 4 commits into from almost 2 years ago

4 participants

Uģis Ozols Philip Arndt Don't Add Me To Your Organization a.k.a The Travis Bot Jean-Philippe Boily
Uģis Ozols
Owner

Originally - #1739

Uģis Ozols
Owner

This probably needs to be squashed?

Philip Arndt
Owner

Squash-ed

Don't Add Me To Your Organization a.k.a The Travis Bot

This pull request fails (merged 77d5016 into 3223ad9).

Philip Arndt
Owner

@ugisozols looks like there's a failing spec ;-)

Don't Add Me To Your Organization a.k.a The Travis Bot

This pull request passes (merged 40b68ae into 3223ad9).

Philip Arndt
Owner

:+1:

Philip Arndt parndt merged commit 8fbf97c into from
Philip Arndt parndt closed this
Uģis Ozols
Owner

I did a poor job while reviewing #1739. It adds several things which make some code useless:

  • every image is sent in a separate post (instead of pushing an array of images) to create action so there's no need to check for array stuff
  • validations are happening on the client side so the validation code in model isn't used anymore (valid? checks in controller are redundant too)

Don't get me wrong @jipiboily - I really like the feature but I'm thinking about reverting this and doing it differently.

Jean-Philippe Boily

No problem @ugisozols. This was an extension at first and implemented it almost as is instead of doing it from scratch, which might be a better idea.

I have minimal experience with Refinery (only one small project, well, project was large, but Refinery's use was tiny) and thought that changing as little as possible would be best to make sure I wouldn't break a non-JS fallback somewhere.

Feel free to make it better! :)

Uģis Ozols ugisozols referenced this pull request from a commit
Uģis Ozols ugisozols Revert "Merge pull request #1903 from resolve/imajax"
This reverts commit 8fbf97c, reversing
changes made to 3223ad9.

Conflicts:
	changelog.md
	images/app/controllers/refinery/admin/images_controller.rb
6c21635
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
1  changelog.md
Source Rendered
@@ -4,6 +4,7 @@
4 4 * Refactored wysiwyg fields into a partial. [#1796](https://github.com/resolve/refinerycms/pull/1796). [Rob Yurkowski](https://github.com/robyurkowski)
5 5 * Shortened all authentication helpers. [#1719](https://github.com/resolve/refinerycms/pull/1719). [Ryan Bigg](https://github.com/radar)
6 6 * Added canonical page id to body to allow CSS selectors to target specific pages instead of including special CSS files. [#1700](https://github.com/resolve/refinerycms/pull/1700) & [#1828](https://github.com/resolve/refinerycms/pull/1828). [Philip Arndt](https://github.com/parndt) & [Graham Wagener](https://github.com/gwagener/)
  7 +* Added ajaxy image uploading. [#1739](https://github.com/resolve/refinerycms/pull/1739). [Jean-Philippe Boily](https://github.com/jipiboily)
7 8
8 9 * [See full list](https://github.com/resolve/refinerycms/compare/2-0-stable...master)
9 10
128 images/app/assets/javascript/refinery/images.js.coffee.erb
... ... @@ -0,0 +1,128 @@
  1 +$(document).ready ->
  2 + images = new Images
  3 + $("#new_image").submit (e) ->
  4 + if window.FileList && FormData
  5 + e.preventDefault()
  6 + images.upload_all()
  7 + $("#image_image").change (e) ->
  8 + images.file_list = e.target.files
  9 +
  10 +
  11 +class Images
  12 + # TODO:
  13 + # - add a progress bar for each file maybe?
  14 + # - refresh images index after closing the dialog box...
  15 + constructor: ->
  16 + @authenticity_token = $("meta[name=\"csrf-token\"]").attr("content")
  17 + @form_action = $("#new_image").attr("action")
  18 + @cache_dom()
  19 +
  20 + cache_dom: ->
  21 + @error_list = $("#error_list")
  22 + @success_list = $("#flash")
  23 + @error_explanation = $("#errorExplanation")
  24 + @upload_progress = $("#upload_progress")
  25 +
  26 + before_upload_all: ->
  27 + @files = []
  28 + @errors = []
  29 + @total_files = @file_list.length
  30 + @uploaded = 0
  31 + @error_explanation.hide()
  32 +
  33 + upload_all: ->
  34 + @before_upload_all()
  35 + for file in @file_list
  36 + @validate(file)
  37 + @files.push file
  38 + return @render_errors() if @errors.length > 0
  39 + $("#submit_button").hide()
  40 + $(".field").hide()
  41 + @progress "<%= ::I18n.t("refinery.admin.images.form.uploading")%>"
  42 + @upload_next()
  43 +
  44 + after_upload_all: ->
  45 + $(".save-loader").hide()
  46 + @upload_progress.hide()
  47 + @success_list.show()
  48 + if @errors.length > 0
  49 + @render_errors()
  50 + else
  51 + if getParameterByName("modal") == "true"
  52 + window.parent.document.getElementById("dialog_frame").contentDocument.location.reload(true);
  53 + else
  54 + window.parent.location.reload(true)
  55 +
  56 + validate: (file) ->
  57 + max_file_size = <%= Refinery::Images.max_image_size %>
  58 + if file.size > max_file_size
  59 + @errors.push "#{file.name} <%= ::I18n.t("refinery.admin.images.form.should_be_smaller")%> #{max_file_size} <%= ::I18n.t("refinery.admin.images.form.bytes_in_size")%>"
  60 + # TODO: set valid file types based on image model validation
  61 + valid_file_types = ["image/jpeg", "image/png", "image/gif", "image/tiff"]
  62 + if valid_file_types.indexOf(file.type) == -1
  63 + @errors.push "#{file.name} <%= ::I18n.t("refinery.admin.images.form.image_type")%>"
  64 +
  65 + upload_next: ->
  66 + @do_upload(@files[0]) unless @files.length == 0
  67 + if @total_files > 0 && @files.length == 0
  68 + @after_upload_all()
  69 +
  70 + do_upload: (file) =>
  71 + form = new FormData();
  72 + form.append "image[image]", file
  73 + form.append "authenticity_token", @authenticity_token
  74 + _this = @ # save current scope so we can use current object methods within $.ajax
  75 + $.ajax
  76 + type: 'POST'
  77 + url: @form_action
  78 + data: form
  79 + contentType: false
  80 + processData: false
  81 + success: (data) ->
  82 + _this.post_success(file)
  83 + error: (data) ->
  84 + _this.post_error(file, data.responseText)
  85 +
  86 + after_do_upload: (file) ->
  87 + @files.remove file
  88 + @upload_next()
  89 +
  90 + post_success: (file) ->
  91 + @progress file.name + " <%= ::I18n.t("refinery.admin.images.form.uploaded")%>"
  92 + @update_progress file
  93 + @after_do_upload file
  94 +
  95 + post_error: (file, errors) ->
  96 + errors = JSON.parse(errors).image
  97 + @update_progress file, errors
  98 + for e in errors
  99 + @errors.push "#{file.name}: #{e}"
  100 + @after_do_upload file
  101 +
  102 + render_errors: ->
  103 + $(".save-loader").hide()
  104 + @error_list.html("")
  105 + for error in @errors
  106 + @error_list.append("<li>#{error}</li>")
  107 + @error_explanation.show()
  108 +
  109 + update_progress: (file, error = null) ->
  110 + @uploaded++
  111 + message = error || "<%= ::I18n.t("refinery.admin.images.form.last_complete")%>: #{file.name}"
  112 + @progress "#{@uploaded}/#{@total_files} <%= ::I18n.t("refinery.admin.images.form.uploaded")%> | #{message}"
  113 +
  114 + progress: (text) ->
  115 + @upload_progress.html(text);
  116 +
  117 +# adds a remove method to Array
  118 +Array::remove = (e) -> @[t..t] = [] if (t = @indexOf(e)) > -1
  119 +
  120 +getParameterByName = (name) ->
  121 + name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]")
  122 + regexS = "[\\?&]" + name + "=([^&#]*)"
  123 + regex = new RegExp(regexS)
  124 + results = regex.exec(window.location.search)
  125 + unless results?
  126 + ""
  127 + else
  128 + decodeURIComponent results[1].replace(/\+/g, " ")
2  images/app/controllers/refinery/admin/images_controller.rb
@@ -54,7 +54,7 @@ def create
54 54
55 55 unless params[:insert]
56 56 if @images.all?(&:valid?)
57   - flash.notice = t('created', :scope => 'refinery.crudify', :what => "'#{@images.map(&:title).join("', '")}'")
  57 + flash.notice = t('uploaded_successfully', :scope => 'refinery.admin.images.form')
58 58 if from_dialog?
59 59 @dialog_successful = true
60 60 render :nothing => true, :layout => true
10 images/app/views/refinery/admin/images/_form.html.erb
... ... @@ -1,3 +1,4 @@
  1 +<% content_for :after_javascript_libraries, javascript_include_tag('refinery/images') %>
1 2 <%= form_for @image, :url => (@url_override or @image.persisted? ? refinery.admin_image_path(@image) : refinery.admin_images_path),
2 3 :html => { :multipart => true } do |f| %>
3 4
@@ -5,6 +6,15 @@
5 6 :object => @image,
6 7 :include_object_name => false %>
7 8
  9 + <% if @image.errors.empty? %>
  10 + <div id="upload_progress"></div>
  11 +
  12 + <div class="errorExplanation" id="errorExplanation" style="display:none;">
  13 + <p><%= t("refinery.admin.error_messages.problems_in_following_fields")%></p>
  14 + <ul id="error_list"></ul>
  15 + </div>
  16 + <% end %>
  17 +
8 18 <div class='field'>
9 19 <% if action_name =~ /(edit)|(update)/ %>
10 20 <p>
9 images/config/locales/en.yml
@@ -15,6 +15,15 @@ en:
15 15 replace_image: " replace it with this one..."
16 16 current_image: Current Image
17 17 maximum_image_size: The maximum image size is %{bytes}.
  18 + uploading: "Uploading..."
  19 + there_was: "There was"
  20 + error: "error"
  21 + should_be_smaller: "should be smaller than"
  22 + bytes_in_size: "bytes in size"
  23 + image_type: "should be either a JPG, PNG or GIF"
  24 + uploaded: "uploaded"
  25 + last_complete: "Last upload complete"
  26 + uploaded_successfully: "Uploaded successfully"
18 27 actions:
19 28 create_new_image: Add new image
20 29 records:
9 images/config/locales/fr.yml
@@ -15,6 +15,15 @@ fr:
15 15 replace_image: " la remplacer par celle-ci..."
16 16 current_image: Image actuelle
17 17 maximum_image_size: "La taille de l'image ne doit pas excéder %{bytes}."
  18 + uploading: "Transfert en cours..."
  19 + there_was: "Il y a"
  20 + error: "erreur"
  21 + should_be_smaller: "devrait être plus petit que"
  22 + bytes_in_size: "octets"
  23 + image_type: "devrait être un fichier JPG, PNG ou GIF"
  24 + uploaded: "transféré"
  25 + last_complete: "Dernier transfert complété"
  26 + uploaded_successfully: "Transféré avec succès"
18 27 actions:
19 28 create_new_image: Ajouter une image
20 29 records:
4 images/spec/requests/refinery/admin/images_spec.rb
@@ -30,8 +30,8 @@ module Refinery
30 30 join("spec/fixtures/image-with-dashes.jpg")
31 31 click_button ::I18n.t('save', :scope => 'refinery.admin.form_actions')
32 32 end
33   -
34   - page.should have_content(::I18n.t('created', :scope => 'refinery.crudify', :what => "'Image With Dashes'"))
  33 + page.should have_content(::I18n.t("uploaded_successfully", :scope => "refinery.admin.images.form"))
  34 + page.should have_selector("img[src*='image-with-dashes.jpg']")
35 35 Refinery::Image.count.should == 1
36 36 end
37 37

Tip: You can add notes to lines in a file. Hover to the left of a line to make a note

Something went wrong with that request. Please try again.