Tips for uploading a file with AngularJS using the multipart/form-data format

Looking for guidance on uploading an image using AngularJS with a REST API that requires Content-Type:multipart/form-data.

Content-Type:multipart/form-data

www.abc.com/images/id
Request Body
{
    // --Boundary_1_1626119499_1392398808202
    // Content-Type: image/png
    // Content-Disposition: form-data; filename="ducky.png"; modification-date="Wed, 05 Nov 2016 19:53:17 GMT"; size=713915; name="upload_image"        

    // {binary data truncated for display}
}

How can I upload an image file using the provided REST API and assign the path to $scope.tempObject?

 $scope.UploadImage =  function () { 
        var config = {headers:  {      
    'Content-Type': 'multipart/form-data'

       }
        }

    $http.post(properties.customerUploadImage_path + "/"+checkprofile,$scope.tempObject,config).success(function (response) { 
 Console.log('Uploaded');
    });


    } 

Answer №1

It seems like you may not be utilizing the $http correctly.

To ensure proper usage, consider utilizing the headers attribute of the $http service in the following manner:

$scope.UploadImage = function () { 
  var config = {
    headers: {      
      'Content-Type': 'multipart/form-data',
    }
  };

  $http({
    method: 'POST',
    url: properties.customerUploadImage_path + "/" + checkprofile,
    data: $scope.tempObject,
    config: config,
  }).success(function (response) { 
    console.log('Uploaded');
  });


};

For further clarification, I recommend referring to the official documentation.

Answer №2

Adjust the headers to include "Content-Type": undefined and utilize the FormData API:

  var config = { headers: {
                   "Content-Type": undefined,
                  }
               };

  vm.upload = function() {

    var formData = new $window.FormData();

    formData.append("file-0", vm.files[0]);

    $http.post(url, formData, config).
     then(function(response) {
      vm.result = "SUCCESS";
    }).catch(function(response) {
      vm.result = "ERROR "+response.status;
    });
  };

In usual cases, the AngularJS $http service utilizes Content-Type: application/json. However, by specifying Content-Type: undefined, the framework will exclude the Content-Type header leading the browser to use its default content type which is multipart/form-data for FormData objects.

Request Header

POST /post HTTP/1.1
Host: httpbin.org
Connection: keep-alive
Content-Length: 388298
Accept: application/json, text/plain, */*
Origin: https://run.plnkr.co
User-Agent: Mozilla/5.0 Chrome/55.0.2883.54 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary9lBDT4yoh8lKWtIH
Referer: https://run.plnkr.co/cW228poRVzWs67bT/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

Request Payload

------WebKitFormBoundary9lBDT4yoh8lKWtIH
Content-Disposition: form-data; name="file-0"; filename="Crop.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary9lBDT4yoh8lKWtIH--

The DEMO on PLNKR.

For further details, refer to:

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

Bootstrap modal experiencing technical difficulties

I am experiencing issues with my bootstrap modal. It seems to be malfunctioning, almost as if the CSS or JavaScript files are not being recognized. I have tried various solutions but have been unable to resolve the problem. I even attempted using the examp ...

Find the ID of the clicked table row using HTML and JavaScript

Currently, I am trying to implement this code snippet: <td align="center"> <div class="dropdown"> <button onclick="DropdownShow(this)" class="btn btn-default glyphicon glyphicon-picture"></button> <div id="@TableR ...

Ways to have a component in Angular 5 patiently await and receive data from another component without the use of an event signal

Seeking assistance with a dilemma involving two components (pop ups) where I need to transfer data from a child component to a parent one that lacks an event to retrieve the data. Essentially, I am looking for a way for the parent to be able to listen fo ...

Having trouble importing components in NativeScript Vue?

I am just starting to explore the world of NativeScript and working on my first project using it. I am facing an issue while trying to incorporate a header component into my main App. Unfortunately, when I run the iOS emulator, the header does not appear o ...

Different ways to send data from JavaScript to Python using the 'POST' method

I have this specific section of code from my GAE application that utilizes webapp2 framework to receive data from a form through the post method. class RenderMarksheet(webapp2.RequestHandler): def post(self): regno = self.request.get('content ...

Issues encountered when retrieving images from directory with AngularJS 1.5 and PHP

The issue I'm encountering is as follows: GET http://localhost/~abhishek/Product/uploads/users/%7B%7Busers.image%7D%7D 404 (Not Found) However, the primary reason for posting this question is that I am developing a product application and need to sa ...

Validating parent in Classic ASP JavaScript

In my project, I am using a Classic ASP file coded in JavaScript to show HTML content. My goal is to detect whether the page is being displayed within a frame or not, and if it's not, redirect it to another page. Is there a way to achieve this in Clas ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

Animating CSS with jQuery for a background image effect

I have the following JavaScript code : $(".linksColl a li").hover(function () { $(this).css({ "background-image" : "url(images/links/linkHover1.png)", "background-position" : "center center", ...

Using function arguments as private variables in JavaScript allows for better encapsulation

Have you ever wondered if function arguments automatically become private variables within the function? I came across this interesting concept and decided to experiment: var node = function(nParent,nName,nContent){ this.init = function(){ ale ...

Tips for always focusing on a textarea within an Angular UI modal when opening the modal

I am facing an issue with setting focus to a textarea within an angular ui modal. I need the focus to be set when the modal is made visible, but it cannot happen during document load as it only works the first time the modal opens. Furthermore, the modal ...

Tips for creating a tabbed form that easily glides between tabs

After coming across this form design, I am inspired to create something similar with a twist. Instead of having each tab display all content at once, I want the tabs to scroll from right to left, giving it a more animated effect. Can someone offer suggesti ...

Unexpected behavior in IE8 with setAttribute following Object extension

In my current project, I've implemented a custom micro-library similar to JQuery, but tailored specifically to my needs. window.$ = function(selector, context, undefined) { var getSelectorTest = function(selector, context, undefined) { ...

Guide on assigning a material to ColladaLoader or OBJLoader

I've searched extensively through the documentation and numerous examples, but I couldn't find the correct syntax for assigning a material to either a Collada .dae or OBJLoader .obj file. Json files seem to work well when creating a Mesh, with t ...

Can you explain the concept of Cross-origin requests?

My JavaScript application is designed to detect single, double right, and double left clicks. A single click triggers an asynchronous request to the HTTP server, while the rest are intended to change the user interface on the client side. However, I am str ...

What is the reason for not being able to utilize the same ID more than once?

This snippet of code may not be complete, but it effectively addresses the issue at hand. <body onload="init()"> <nav> <h1 style="font-family:Helvetica;"> <ul class="nav"> <li ><a href="#">Me ...

Tips for refreshing scope when the ng-model value changes upon form submission

As I work on creating an edit customer form and passing an object containing 30 key value pairs, I encounter a challenge. I use ng-repeat to populate input fields on the form with the passed key values, and everything displays nicely. I can make changes to ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

Express JS encountering issue with static files serving

Despite encountering this common issue, I have struggled to find a solution to properly serve my static files with express after trying various methods. The folder structure of my app is as follows: .. -bin -lib -run -etc -node-modules -public --css ---s ...