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

Are promises returned by all API functions in Protractor?

During my test run: browser.get('http://www.valid-site.com').then(function(msg){ console.log(msg); }); I was anticipating the output to be either 1 or true, signifying a successful operation since get() is supposed to return a promise with ...

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Switch between different table rows

I have here a table that is used for displaying menu and submenu items. It's a mix of PHP (to fetch the menu items and their respective submenus) and HTML. What I am trying to figure out is how to toggle the visibility of only the submenu items under ...

Manipulating a React table: Customizing a row in the table

Below is the code snippet: const [data, setData] = useState([ {id: 1, name: 'paper', qty: 10}, {id: 2, name: 'bottle', qty: 10}, ]); const [isEditable, setEditable] = useState([]); useEffect(()=>{ data.map(each=>{ ...

Examining the scroll-down feature button

I'm currently experimenting with a scroll down button on my website and I'm perplexed as to why it's not functioning properly. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" c ...

Tips for choosing elements in JavaScript using querySelector even after they've been included in the code using innerHTML

Within the scenario below, a parent element is present in the HTML code and the span element with a class of 'child' is nested within the parent element using the createChild function. Subsequently, the content of the child element is modified el ...

Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution: <ng-container *ngIf="user.images.length > 0"> <div *ngFor="let image of images"> <img *ngIf="i ...

Set YouTube Playlist to start from a random index when embedded

I've been trying to figure out how to set my embedded playlist to start with a random video. Here's what I attempted: <iframe src="https://www.youtube.com/embed/videoseries?list=PLPmj00V6sF0s0k3Homcg1jkP0mLjddPgJ&index=<?php print(ran ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

Transferring data between modules using Ajax or services in React.js

I have a React application where I need to pass data received in one component to another. After receiving the data successfully, I set the state and then try to pass this data as a property to the next component. However, when I try to access this passed ...

Having trouble retrieving data from JSON using JavaScript

Hey folks, I need some help with the following code snippet: function retrieveClientIP() { $.getJSON("http://192.168.127.2/getipclient.php?callback=?", function(json) { eval(json.ip); });} This function is used to fetch the IP address of visitors. When i ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

The server remains unreachable despite multiple attempts to send data using Angular's $http

I am encountering an issue with triggering $http.post: app.controller('editPageController', function($scope, $routeParams, $http) { $scope.page = $routeParams.pageid; // retrieve page data from the server $http.get('/pages/&ap ...

When using react-hook-form to upload an image field, it functions properly on the frontend, but when accessing it through a next.js API route, the req.body.image is

This section contains key frontend code: Input registration: return ( <form onSubmit={handleSubmit(onSubmitForm)}> <input {...register("image")} type="file" /> </form> ); } Function to handle for ...

Is it not possible to use GLOB with JSHint on Windows operating systems?

Currently, I am experimenting with using NPM as a build tool (). My experience with NPM is limited, and at the moment I only have JSHint and Mocha installed. Attached is my package.json file. However, when I try to run "npm run lint" in the Windows 7 comma ...

The hamburger menu for mobile devices is not functioning properly on the website's mobile version, however it operates correctly when the screen is resized

Currently, I am facing an issue with the hamburger menu not responding on my mobile device. Oddly enough, it does work when I resize my browser window to mimic a mobile size. There seems to be a glitch happening, but I'm struggling to pinpoint the exa ...

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Angular 1.5 component causing Typescript compiler error due to missing semi-colon

I am encountering a semi-colon error in TypeScript while compiling the following Angular component. Everything looks correct to me, but the error only appears when I insert the this.$routeConfig array: export class AppComponent implements ng.IComponentOp ...