How to implement redirect after upload with Rails 3 and Plupload?

Every time I use plupload to upload a file using the code below, I notice in the Firebug console that there is a message in red indicating POST /uploads 200 OK 8192ms. Upon further inspection of the terminal output, I see Completed 200 OK in 7653ms.

var uploader = new plupload.Uploader({
    runtimes: 'gears,html5,flash,silverlight,browserplus',
    browse_button: 'pickfiles',    
    autostart : true,    
    max_file_size: '10mb',
    url: '/uploads',
    resize: { width: 320, height: 240, quality: 90 },
    flash_swf_url: '/Scripts/pl/plupload.flash.swf',
    silverlight_xap_url: '/Scripts/pl/plupload.silverlight.xap',
    filters: [
    { title: "Image files", extensions: "jpg,gif,png" },
    { title: "Zip files", extensions: "zip" }
]
});
uploader.bind('Init', function (up, params) {
    $('#filelist')[0].innerHTML = "<div>Current runtime: " + params.runtime + "</div>";
});
uploader.bind('Error', function (up, err) {
    $('#filelist').append("<div>Error: " + err.code +
        ", Message: " + err.message +
        (err.file ? ", File: " + err.file.name : "") +
        "</div>"
    );

});
uploader.bind('FilesAdded', function (up, files) {
    for (var i in files) {
        $('#filelist')[0].innerHTML += '<div id="' + files[i].id + '">' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';
    }
    //uploader.start();
});
$('#uploadfiles').click(function (e) {
    uploader.start();
    e.preventDefault();
});

uploader.bind('UploadProgress', function (up, file) {
    $('#' + file.id)[0].getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
});

uploader.init();

In the Uploads controller, the create action looks like this:

  def create
    @upload = Upload.new(:upload => params[:file])

    if @upload.save
      head 200
      #redirect_to '/users'
    else
      render :action => "new"
    end
  end

I'm trying to figure out how to redirect to another page after finishing an upload. Even though I attempted to redirect to the users page in the create action with head 200, nothing happens.

If anyone could provide guidance on how to achieve this redirection after an upload completes, I would greatly appreciate it. I've searched online but haven't found a solution yet...

Lastly, why does the Firebug console always show POST /uploads 200 OK without any accompanying log message after uploading a file?

Answer №1

To easily achieve this task, I utilized the window.location javascript function. Plupload offers an uploadcomplete Event that triggers once all the file uploads are finished. Additionally, the FileUploaded event is triggered after each individual file upload. Therefore, the uploadcomplete event proves to be beneficial when you intend to upload multiple files concurrently. The concept of the uploader was inspired by a reference found here, with the inclusion of the upload complete event. Below is my implementation of the uploader:

<script type="text/javascript">
 $(function(){
  var uploader = new plupload.Uploader({
   runtimes : "html5",
   browse_button : 'pickfiles',
   max_file_size : '100mb',
   url : "/documents",
   multipart: true,
   multipart_params: {
   "authenticity_token" : '<%= form_authenticity_token %>'
  }
});

 uploader.bind('FilesAdded', function(up, files) {
  $.each(files, function(i, file) {
  $('#filelist').append(
    '<div id="' + file.id + '">' +
    'File: ' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>'
    );
  });
 });

  uploader.bind('UploadProgress', function(up, file) {    
     $('#' + file.id + " b").html(file.percent + "%");
  });

  uploader.bind('UploadComplete', function(up, files) {
     window.location = '/documents';
  });

  $('#uploadfiles').click(function(e) {
     uploader.start();
     e.preventDefault();
  });

  uploader.init();
 });

</script>

Upon completion of the upload process, the uploader automatically redirects to display all the uploaded documents.

Answer №2

Here are a couple of options to handle redirecting:

1) Utilize Plupload's FileUploaded callback function for redirecting after successful upload:

uploader.bind('FileUploaded', function(up, file, info) {
  // Redirect to 'http://mysite.com/users'
  window.location = 'http://mysite.com/users';
});

2) Alternatively, you can rely on Rails to handle the redirect by adding this code snippet to your ApplicationController:

# Implement redirect functionality for AJAX and non-AJAX requests
def redirect_to(options = {}, response_status = {})
  if request.xhr?
    render(:update) {|page| page.redirect_to(options)}
  else
    super(options, response_status)
  end
end

Answer №3

Redirecting in the way you described is not possible when uploading files with any upload runtime because it is considered an indirect action. HTML5 utilizes XHR, HTML4 uses a proxy iframe, and flash/silverlight have their own byte streaming APIs for file uploads.

If you are only uploading one file at a time, your best option is to utilize the FileUploaded event. The third parameter will contain the server response from all runtimes. Here is an example of how you could use it (based on information provided by iWasRobbed):

uploader.bind('FileUploaded', function(up, file, info) {
  // Redirect after successful upload
  window.location = info.response;
});

The response will be plain text as plupload can only standardize this across different runtimes. Therefore, your redirect URL should be included in the body of the response. If you require more complex responses, you can send serialized JSON and parse it on the client side.

Answer №4

Although this information may be a bit dated, I am looking to enhance the responses provided. Building off of @gonchuki's suggestion, I made some adjustments to my view:

uploader.bind('FileUploaded', function(up, file, info) {
  window.location = info.response;
});

In my controller, I simply render the URL with plain text:

def create
  # implement functionality here
  render :text => object_path(id: object)

I hope this also proves helpful :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retain the previously selected option in a PHP combobox even when changing pages

Can someone please assist me with my PHP code? I am having trouble keeping my combobox unchanged after a page reload. It works fine until I change pages in my pagination. Can anyone help? THIS IS MY PHP. PHP ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

I attempted to write an AngularJS code, however, it seems to be malfunctioning

Here is a snippet from my controller.js file: angular.module("ngcribs").controller("cribsController", function($scope) { $scope.message = "Hello, world!"; }); And here is a section of my index.html file: <!DOCTYPE html> <html lang="en"&g ...

Styling pagination using CSS and jQuery

I am looking to display 3 sections in a simple, paginated way that mimics tabs. I am trying to implement the logic where when a pagination item is clicked and has the 'active' class, it should show the corresponding block. However, I am strugglin ...

Tips for setting up a webpacked vue.js application with an express/koa backend!

Struggling with setting up a vue.js project for easy debugging in combination with a koa server? The cross-env NODE_ENV=development webpack-dev-server --open --hot command from the webpack-simple generated configuration looks promising, but how should it b ...

Create a jQuery script that generates clickable links when a user is mentioned in the

Hey there, I've been incorporating this fantastic plugin created by Hawkee into my project. It functions similarly to Twitter, allowing users to @mention others. However, I'm encountering issues with the output when using the following method: u ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

Changing the dimensions of a div according to the container's size

I'm currently working on a project that involves an HTML video player with custom Javascript controls, utilizing SVG graphics for the backgrounds. However, I've encountered an issue with using the css calc() function to resize the divs based on t ...

"Is there a way to modify the color of the button once it's been clicked, but only for the specific button that was

Looking to create a Quiz App using React and facing an issue where all buttons change color when clicked, instead of just the one that was clicked. Any solutions on how to make only the clicked button change its color in React.js? App.js import Main from ...

Problem with Layering in Javascript Canvas Game using Kinetic JS

Currently, I am attempting to replicate the game found at and delving into html5 canvas and kineticJS for my study. Here is the link to my fiddle: http://jsfiddle.net/2WRwY/7/ The issues I am facing are as follows: The tail part of the player in the f ...

Upon refreshing the page, Vuex encounters an issue where it is unable to read

My website has a Navbar component that utilizes values from the Vuex store. Prior to entering each route, I trigger a dispatch from Vuex as shown below: router.beforeEach((to, from, next) => { //... store.dispatch("updateUserData"); ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

What is the method used by Disqus to adjust the size of its iframe according to the content it contains?

Check out this interesting example article: If you scroll down to the comments section, you'll notice that Disqus inserts an iframe onto the page, and then loads the comments inside the iframe. The intriguing part is that the iframe automatically ad ...

Issues with reading d3.js visualization data from a JSON file

I am currently working on a data visualization project using D3.js and I started with a basic framework that I found on this link The data for my visualization is coming from a json file containing only two values, a string value and an integer. However, ...

Utilizing jQuery to attach events to dynamically generated elements

I have a scenario where I am uploading multiple images and inserting them into specific div elements. These divs should toggle a class when clicked. Should I include the part of code that adds the onclick event inside the ajax success function? Your help i ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

Scheduling a cron job to run at a particular date and time

Our express js application includes a feature in the admin module where users can send emails at specific dates and times they select. For example, if the chosen date and time is [email protected], we need to execute the email code at that exact time ...