I am facing difficulty in accessing the response with angular when using multer

I am utilizing Multer for uploading photos. My backend technology is Node, and I have managed to successfully upload the image. However, upon uploading the image and receiving the response back in Angular via json, all I see in the console log is [object Object]. Despite attempting to use stringify, I cannot view the response in the UI. Understanding and working with responses often proves challenging for me, and I am eager to finally grasp this concept. The HTML displays nothing.

Response from my Node.js server:

apiRoutes.post('/admin/photos',upload.single('file'),function(req,res){
  console.log(req.file);
  res.json(req.file);
});

Angular Upload:

$scope.submit = function() {
  if ($scope.file) {
    $scope.upload($scope.file);
  }
};

// Function to handle file upload on select or drop
$scope.upload = function (file) {
  Upload.upload({
    url: '/api/admin/photos',
    headers : {
    'Content-Type': 'multipart/form-data',
    },
    data: {file: file}
  }).then(function (resp) {
       console.log('Success ' + resp.config.data.file.name + ' uploaded. Response: ' + resp.data);
       $scope.myPic = resp.config.data.file.name;       
  }, function (resp) {
         console.log('Error status: ' + resp.status);
  }, function (evt) {
         var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
         console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
  });
 };
}]);

HTML:

<form ng-controller="adminController" name="form" enctype="multipart/form-data">
  Single Image with validations
  <div class="button btn btn-default" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
    ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" 
    >Select</div>
  <button type="submit" ng-click="submit()">Submit</button>
</form>

<p>{{ myPic }} </p>

<ul ng-repeat="picture in myPic">
    <li>{{ picture }} </li>
</ul>

Answer №1

In my opinion, it is not advisable to send the file back from the server. Instead, you can extract the file details on the client side using $scope.file:

http://jsfiddle.net/6jh0sb5n/3/

<input type="file" ngf-select ng-model="file" name="file"    
         accept="image/*" ngf-max-size="2MB" required
         ngf-model-invalid="errorFiles" ng-change="getFileDetail()">

.then(function (resp) {
    alert('filename:' + $scope.file.name + ',size: ' + $scope.file.size);
}

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

Using Javascript to efficiently remove elements with AJAX

Currently, I am learning the basics of HTML and focusing on tasks such as login/logout functionality, creating users, and deleting users (only permitted when logged in as an admin). For updating a user password, I have utilized PUT, for creating a user ac ...

Resolving Unicode Problems with Angular in Firefox

I am currently utilizing the angular-translate module within my application. While it functions properly in Chrome, I have encountered issues in Firefox when attempting to utilize language files that contain unicode characters. Upon direct browsing of a j ...

Show information in a table based on a unique identifier

I am working with some data that looks like this [ { date: '20 Apr', maths: [70, 80.5, 100], science: [25, 20.1, 30] }, { date: '21 Apr', maths: [64, 76, 80], science: [21, 25, 27] }, ]; My goal is to present ...

Passing JSON Data Between Functions within an Angular Controller

In my current setup using Node.js, Angular, Express, and HTML, I have a text area that gets filled with formatted text data for letters when certain buttons are clicked. <div class="form-group"> <label class="control-label" for="flyer descriptio ...

Effectively implementing an event observer for dynamically loaded content

I want to set up an event listener that triggers when any of the Bootstrap 3 accordions within or potentially within "#myDiv" are activated. This snippet works: $('#myDiv').on('shown.bs.collapse', function () { //code here }); Howeve ...

Error: Unable to perform 'getComputedStyle' on the 'Window' object: the first parameter must be of type 'Element'

My goal is to create a rotating effect with a center circle containing 5 inner divs. When the device is rotated on the gamma axis, I want the circle div to rotate in accordance with the gamma degree, while the inner divs rotate in the opposite direction to ...

Angular BehaviorSubject is failing to emit the next value

I am facing an issue with a service that uses a Behavior subject which is not triggering the next() function. Upon checking, I can see that the method is being called as the response is logged in the console. errorSubject = new BehaviorSubject<any> ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Tips for choosing an image using jQuery from an external HTML page

I'm attempting to embed an HTML page within a div and then individually select all the img tags within that page to display an overlay div on top of the images. Currently, I can insert the HTML into a div named "asd" and it seems like the jQuery is f ...

Is it possible to simultaneously utilize a Node.js server and an ASP.NET web service?

Although I have experience in developing with .NET, I am new to Node.js and intrigued by its advantages. I believe it is a great way to maintain code and promote reusability. However, I am faced with a dilemma. I understand that Node.js allows for creatin ...

Protractor - selecting a hyperlink from a list

Imagine you have a todo application with tasks listed as follows: Walk the dog, Eat lunch, Go shopping. Each task has an associated 'complete' link. If you are using Protractor, how can you click on the 'complete' link for the second t ...

javascript - disable screen capture of specific parts of a webpage

Recently, I've come across certain web pages that have a unique feature preventing screen capture of specific regions. When attempting to take a screenshot using Chrome, some areas that are visible on the live page appear as black frames in the captur ...

What is the best way to assign string values from an array in data() to the src attribute of an image element?

I've been working on a feature where the <div.box> element appears based on the user's input through a form. In this project, I'm using vue3 and v-for to iterate over an array 'images' that contains URL strings linking to ima ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...

I am looking to build an array that can store five numbers inputted by the user. Following that, I want to utilize a for loop to display the contents of the array. How can I accomplish this task?

Looking for help to store 5 unknown numbers in an array and then display them after the user has entered all 5 numbers. Can anyone assist me in creating an array of size 5 and using a for loop to show the numbers? Here is the code I currently have: ...

"Problems arise with mongodb full $text search when sorting and filtering, causing duplicate items to

When using full-text search in my API and sorting by score, I am encountering an issue where the same item is returned multiple times. This behavior is not what I expected. How can I correct this to ensure unique results? Below is the structure of my rout ...

Could someone please explain why my ajax is not functioning properly?

I have been working on an AJAX function to pass input values from one page to another. However, I am facing a challenge where the value is not being passed as expected after redirection. Despite my efforts, I cannot figure out why it's not functionin ...

Removing a row from an HTML table using JavaScript

I have a piece of JavaScript code that is responsible for managing an HTML table. One of the functionalities it needs to support is deleting a row from the table. Currently, I am using the following snippet of code to achieve row deletion: var rowToDele ...

Angular encountering injector error yet still successfully returning variables

It seems like I am facing a simple problem that I might be overlooking, as I have similar functions working fine in other controllers. However, for some reason, I'm encountering this error: Error: [$injector:unpr] Unknown provider: tourinfoProvider & ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...