The file object appears to be empty when attempting to send it to the server using ng

Using ng-file-upload, I am attempting to upload a single file to my server.

After selecting the file and passing the file object ($scope.myFiles[0]) to my angular service, I noticed that when inspecting the HTTP request in the developer tools, the file object appears to be empty.

Controller:

UploadService.upload( { data: { file: $scope.myFiles[0], 'category': $scope.selectedCategory}})
    .success(function (data) {
    ////
    ////

UploadService:

app.factory('UploadService', function ($http, $q) {
    return {
        upload: function (something) {
            console.log(something);

            return $http({
                method: 'POST',
                url: '/upload',
                data: something
            });
        }
    }
});

Upon inspecting the HTTP requests in the developer tools, this is what I see:

Request Payload:
    {data: {file: {}, category: "Friend Card"}}
     data:
         {file: {}, category: "Friend Card"}
         category:"Friend Card"
         file:{}

By checking the output of console.log(something), I can confirm that the file information is available:

{
    $hashKey:"object:107"
    lastModified:1465716430000
    lastModifiedDate:Sun Jun 12 2016 08:27:10 GMT+0100 (BST)
    name:"Postcard.JPG"
    size:522622
    type:"image/jpeg"
    webkitRelativePath:""
}

I made adjustments to the function to include a header type as follows:

return $http({
            method: 'POST',
            url: '/upload',
            headers: {
                'Content-Type': something.data.file.type
            },
            data: {
                "file": something.data.file,
                "category": something.data.category
            }
        });

Upon inspecting the developer tools, I noticed:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:48
Content-Type:image/jpeg
Cookie:_ga=GA1.1.2023678669.1463291637; _gat=1
Host:localhost:8585
Origin:http://localhost:8585
Referer:http://localhost:8585/pages/

Even with the correct Content-Type specified as image/jpeg, the file object is still empty.

Answer №1

A portion of the answer was inspired by a previous response from danial...

The ng-file-upload library offers a variety of APIs and methods that can be added to your angular application, including the 'Upload' service.

I added this service to my controller and followed the example provided in this jsFiddle: http://jsfiddle.net/danialfarid/maqbzv15/1118/

Upload.upload({
  url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
  data: {username: $scope.username, file: file},
});

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

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

What causes the interference of one Import statement with another?

In the JavaScript file I'm working with, I have added two import statements at the beginning: import { FbxLoader } from "./ThreeJs/examples/jsm/loaders/FBXLoader.js"; import * as Three from "./ThreeJs/src/Three.js"; However, when ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Guide to implementing setTimeout in a .map() function in ReactJS

I am currently working on a project that involves an array of players. Whenever a user adds a new player to this array, I need it to be displayed one at a time with a 500ms interval between each player. Below is the code snippet I have written for this f ...

When attempting to import Three.js canvas on Github Pages, a 404 error is received

While attempting to host my webpage with a three.js background, I encountered an issue where everything loads properly when hosted locally, but nothing loads when pushed to GitHub pages - only the HTML is visible. I am utilizing Vite to package my code an ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

Is there a way to launch a browser in full screen mode using a command line interface?

Is there a clever way to launch a web browser in full screen mode from the command line? The browser's full screen API only activates in response to user interaction. I simply want to show data on a large monitor without any unnecessary elements lik ...

Load certain database information into memory as Express initializes

Are there any efficient methods for storing data in Express? For instance, I am interested in preloading all API keys from a PostgreSQL database into memory when the server is initialized to avoid having to query the database for each API request. I consi ...

JQuery Ajax request functioning smoothly while native JavaScript falls short

I am currently troubleshooting two AJAX calls. One is written in native JavaScript while the other utilizes JQuery to call a PHP script. The jQuery AJAX call seems to be functioning properly, but I am encountering issues with the JavaScript version. Here i ...

Update the appearance of a cell if the value within it is equal to zero

I have discovered a way to achieve this using inputs. input[value="0"] { background-color:#F7ECEC; color:#f00;} Now, I am looking for assistance in applying the same concept to table cells. Can anyone provide guidance? Thank you. ...

When working on a Vue project, the Navbar @click functionality seems to

Having trouble with my navbar search form <form action="" method="post" class="search"> <input type="text" name="" placeholder="поиск" class="input" v-model="alls ...

(MUI Textfield) Error: Unable to access properties of undefined (specifically 'focus')

I have been working with the useRef hook in my Material Ui Textfield and have encountered the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus'). I am unsure how to resolve this issue. Here is my current code snippet: ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...

What is the local date format for the Ionic DatePicker?

I have successfully implemented a DatePicker in my Ionic Project, but the date is displaying in the wrong time format. Here is my function: showDatePicker(){ this.datePicker.show({ date: new Date(), mode: 'date', allowOldDates: fal ...

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

"Learn the technique of animating SVG paths with JavaScript, a step beyond traditional HTML filling

I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes. Some helpful links I found: Fill color SVG path w ...

Implementing a post request triggered by a button click in Node.js with Express

How can I invoke a controller from a button click event? I tested it in Postman and it works fine, but I'm having trouble calling it from a button on my front-end. I am using Nodemailer and Node Express to send emails. Here is my code. Can someone p ...

Result of a callback function

Having trouble returning a value for form validation using a callback function. It's not working for me... <form action="loggedin.php" onsubmit="return test(valid)" method="post"> function test(callback) { var k = ""; var httpRequest = ...

Attempting to eliminate the readonly attribute from HTML using Python

Seeking assistance with removing the readonly tag from an input field using Python and Selenium. Can anyone lend a hand? Datepicker Image: HTML: <input id="startDate" name="START_DATE" type="text" class="date hasDate ...

What steps do I need to follow to create a controller component for a Form Element

I am trying to create a dynamic controller component in React Native, but I am facing issues with accessing errors. I am using "react-hook-form" for form elements. Here is my component: const { control, handleSubmit, formState: {errors}, ...