Uploading files in AngularJS using Rails Paperclip

I have been working on implementing a file upload feature with AngularJS/Rails using the Paperclip gem. I was able to resolve the file input issue with a directive, but now I am facing an issue where the image data is not being sent along with other post data.

Here is my HTML code:

<form name="PostForm" ng-submit="submit()" novalidate>
  <input type="text" ng-model="post.title">
  <input type="file" file-upload />
  <textarea ng-model="post.content"></textarea>
</form>

This is my controller:

$scope.create = function() {

    function success(response) {
        console.log("Success", response)
        $location.path("posts");
    }

    function failure(response) {
        console.log("Failure", response);
    }

    if ($routeParams.id)
        Post.update($scope.post, success, failure);
    else
        Post.create($scope.post, success, failure);
}

$scope.$on("fileSelected", function (event, args) {
    $scope.$apply(function () {
        $scope.post.image = args.file;
    });
});

This is my model:

class Post < ActiveRecord::Base
  attr_accessible :content, :title, :image_file_name, :image_content_type, :image_file_size, :image_updated_at

  belongs_to :user
  has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
end

However, when I send the data to the server side, the request does not include any information about the image:

{
  "content":"Hey",
  "created_at":"2013-08-31T17:54:32Z",
  "id":17,
  "image_content_type":null,
  "image_file_name":null,
  "image_file_size":null,
  "image_updated_at":null,
  "title":"Image",
  "updated_at":"2013-08-31T17:54:32Z",
  "user_id":4
}

Any suggestions on how I can ensure that the image data is also sent to the server?

Answer №1

After successfully sending file data using form-data content type, I encountered an issue with the Rails controller resulting in the following error:

undefined method `stingify_keys`

Here is the code snippet I utilized to transmit the data:

$http({
        method: 'POST',
        url: url,
        headers: { 'Content-Type': false },
        transformRequest: function (data) {
            var formData = new FormData();
            formData.append("post", angular.toJson(data.post));
            formData.append("image", data.image);
            return (formData);
        },
        data: { post: $scope.post, image: $scope.image}
    }).
success(function (data, status, headers, config) {
    alert("success!");
}).
error(function (data, status, headers, config) {
    alert("failed!");
});

These are the data being sent to the Rails server:

-----------------------------2122519893511
Content-Disposition: form-data; name="post" {"title":"sdsdsd","content":"sdsd"}
-----------------------------2122519893511
Content-Disposition: form-data; name="image"; filename="dad.jpg" Content-Type: image/jpeg [image-data]
-----------------------------2122519893511--

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

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

Paginating content without the need for a database

Seeking assistance on implementing pagination for displaying trading history API responses, without utilizing a database. Can anyone provide guidance and help with the necessary logic? Here is an excerpt of my code: <?php error_reporting(E_ALL) ...

Unable to update the scope upon $emit in the component

In my AngularJS component, I have a value stored in the scope that provides a URL to an <img> element in the view. Whenever a user changes the image, the controller emits a change using $rootScope.$emit, causing the URL value to update. Ideally, the ...

What is the reason behind the default disabling of bootstrap multiselect options?

Just diving into the world of bootstrap and I'm puzzled as to why my simple multiselect options aren't responding when clicked. UPDATE The first multiselect option on the test-site linked below is the one giving me trouble. I've tried it o ...

Storing the CSS styling for a unique directive in its own dedicated file

Currently exploring Angular and seeking guidance on the most effective methods, as well as a general roadmap for delving deeper into the topic: In my efforts to develop a web application with Angular consisting of various independent widgets, I have opted ...

Having trouble passing data from router to View with EJS in Express. Despite trying, still encountering ReferenceError message

I encountered an issue when trying to display form errors to the user. I attempted to pass the errors from the router to my view file. Error Message ReferenceError: e:\2016\passport\views\register.ejs:38 36| 37| <div ...

How do I set up a slideshow to loop continuously?

I created a slideshow for my website using the script below, but I'm struggling to figure out how to make it repeat. I want the slideshow to go back to the first photo after reaching the last one. Can anyone help please? For reference, please check o ...

"Following successful POST login and session storage in MongoDB, the session is unable to be accessed due

When sending login data by POST with the credentials: 'include' option from client server 5500 to backend server 3000, I ensure that my session data is properly stored in MongoDB thanks to the use of 'connect-mongodb-session'. In the ba ...

Using Vue 3's emit in place of v-model

I am facing a challenge with integrating a custom dropdown select component. The idea is to use v-model to retrieve data from the parent component, but I am unsure how to pass that through an emit. Can anyone clarify this for me? Here is my parent compone ...

Prevent image upload until text is clicked on

When the user clicks on the mask image, a file upload dialog box is displayed. Once the user uploads an image, the text "Remove Image" is shown. Issue: Currently, users can upload another image before clicking on "Remove image". However, after clicking o ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

You can't send headers to the client in Express after they have already been set

I successfully registered and inserted a record in my MongoDB. However, I encountered an error when trying to log in at the line "!user && res.status(401).json("Wrong User Name");" Cannot set headers after they are sent to the client at new NodeError ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

When attempting to post data using jQuery, an object is encountered that does not have a parameterless constructor

Here is the code snippet I am using with jQuery to post data and register a band: var formData = new FormData(); var file = document.getElementById("CoverPicture").files[0]; formData.append("file", file); var Name = $('#Name').val(); var Genre = ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

What is causing the error message of "prop id does not match the rendered server output" to appear on my screen?

https://i.stack.imgur.com/VOLDT.png I've been working on a nextjs redux project and I keep running into this error whenever I refresh my page. Despite searching for a solution, I haven't been able to resolve it. The official next js blog suggest ...

Managing input/output requests on Amazon EC2 instances

Having mastered node, javascript, and other technologies the hard way, I am finally on the brink of releasing my debut web application. After signing up for Amazon Web Services and setting up a micro instance to take advantage of the first year's free ...

The website functions well in responsive design mode on an iPad screen, but encounters issues when viewed on an actual

The website is functioning well in responsive design mode on an iPad screen, however it seems to be having some issues specifically on iPad devices. I have tested it on all other devices and it works perfectly fine, but for some reason not on iPads. Feel ...