Uploading Multiple Parts to Spring REST API with Angular Factory Service and $resource Module

I am currently using AngularJS to interact with a RESTful web service (which is powered by spring boot) via $resource. My goal is to upload files and send form fields in a single multipart post request, but I encountered the following error:

When trying to upload, I received an "Unsupported Media Type" exception with the message: "Content type 'application/xml' not supported", path: "/study/upload", status: 415

Below is my view form:

<form method="post" enctype="multipart/form-data" ng-submit="submit()">
  <table>
    <tr><td>File to upload:</td><td><input type="file" name="file" ng-model="form.file"/></td></tr>
    <tr><td>Name:</td><td><input type="text" name="name" ng-model="form.name"/></td></tr>
    <tr><td></td><td><input type="submit" value="Upload"  /></td></tr>
  </table>
</form>

This is how the view controller looks like:

$scope.submit=function(){
    GalleryService.upload({file: $scope.form.file, name: $scope.form.name}, function(data) {
         console.log("Success ... " + status);
    }, function(error) {
         console.log(error);
    });
}

The gallery.service :

(function() {

'use strict';

angular .module('ekellsApp') .factory('GalleryService', GalleryService);

The GalleryService function goes here:

function GalleryService($resource, restApi) {</p>
  
<pre><code>return $resource(restApi.url + '/study/:action', {},{
 save: {method: 'POST', params: {action: 'save'}},
 getAll: {method: 'GET', params: {action: 'getAll'},isArray:true},
 upload: {method: 'POST', params: {action: 'upload'}, transformRequest: angular.identity,headers: { 'Content-Type': undefined }}
});

}

})();

Lastly, this is how the REST controller is defined:

@RequestMapping(value = "/upload",method = RequestMethod.POST,headers = "content-type=multipart/*")
public String handleFileUpload(@RequestParam("name") String name,
                               @RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
        return "redirect:upload";
    }
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
        return "redirect:upload";
    }

    if (!file.isEmpty()) {
        try {
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File("user/bouhuila/" + name)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded " + name + "!");
        }
        catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    }
    else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:upload";
}

Answer №1

It's unclear what

 GalleryService.upload

is accomplishing, but it seems like the form may not be fully submitted to the server and only certain fields are being sent. In this scenario,

enctype="multipart/form-data"

would not be necessary, which could potentially explain the error message you're encountering.

I suggest checking the developer tools in your browser to see exactly which request is being sent to the server and what content type is being used.

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

Why AngularJS's ng-repeat track by obj.id fails to reinitialize transcluded content upon obj.id change

function ManageComponent() { var newVar = this; this.$onInit = function() { newVar.linkURL = 'http://example.com/obj/' + newVar.obj.id; } } function MasterController($scope, $timeout) { $scope.arrObjs = [{id: 1, name: "item1"},{id: 2, ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

Finding the element '54' using protractor, without relying on xpath

Having trouble finding the number 54 (or the entire internal div) in this HTML snippet. I prefer not to use xpath since my page structure changes based on search results. Is there a way to locate it using CSS, maybe? PS: I'm testing an Angular applic ...

Sending a list of custom objects including images via AJAX to a REST API in a Spring Boot application

Encountering a problem with an Ajax call when passing a List of custom objects with images to a REST API in Spring Boot. Below is a snippet of my code. Controller @PostMapping(value = { "/test/saveUser" }, consumes = { "multipart/form-data& ...

Incorporating object data and a value into an Angular $http.post request and retrieving them in an ASP .NET Web API

I am seeking a way to send multiple objects and a value from an Angular application to an ASP .NET Web API. Below is the snippet of my JavaScript code: var productStockArray = $scope.ProductStockArray; var challan = 20; $http.post(dataUrl + "StockProduc ...

AngularJS carousel slider not functioning properly due to issues with AJAX integration

When I initially add a static array, the slider works fine. However, when I try to load data using AJAX like this: $http.get(baseurl + 'controller/getimagesData/').success(function(data) { $scope.bestDeals = data; ...

The removal of an object becomes unsuccessful when objects with lower indices have been deleted beforehand

Attempting to construct a multi-layer object representing a program; check out my progress here http://codepen.io/Irish1/pen/lbjdw Imagine adding 3 weeks, each with 3 days, and each day having 3 sessions. Removing these objects is feasible as long as caut ...

Display the list in a grid format with 4 columns and x number of rows by utilizing Angular and Bootstrap

I need to display a list of values [1,2,3,4,5,6,7,8,9,10] as a bootstrap grid (class="col-x") using AngularJS. My goal is to create a grid with 4 columns and 3 rows from this list. Can you suggest the most efficient method to achieve this? ...

Access social media login functionality from the client side using AngularJS

I am currently implementing social login in Angular using satellizer. However, I came across a section in the documentation that mentions the need for server-side code as well. The specific lines are provided below: "Additionally, authorization (obtaining ...

Is it possible to adjust the color of the iOS status bar using NativeScript, Angular 2, and TypeScript?

I recently came across this npm package called NativeScript Status Bar, available at the following link: https://www.npmjs.com/package/nativescript-statusbar However, I'm facing an issue because I cannot use a Page element as I am working with Angul ...

The authentication method "local" in nodejs-mysql is unrecognized

Currently, I am working on an application that combines Angular, Node, and MySQL. My main focus right now is implementing a login feature using passport.js. However, I keep encountering the error message "unknown authentication strategy 'local'". ...

Retrieve information from an ajax call within an Angular application

I need assistance with 2 requests I have. $.ajax({ type: "POST", url: "http://sandbox.gasvisor.com:9988/uaa/oauth/token", data: "grant_type=client_credentials", headers: { 'Content-Type': 'application/x-www-form-urlencoded&a ...

Establishing a connection with Taffy DB using Node.js

Currently, I am in the process of developing an application that utilizes Angular js, Node js, and Taffy DB. The main challenge I am facing involves storing the data submitted from the front-end into Taffy DB through the Node js server. var express = req ...

What could be causing the missing key value pairs in my JSON parsing process?

I have set up a Rails backend to serve JSON data, such as the example below from 2.json: {"id":2,"name":"Magic","location":"Cyberjaya","surprise_type":"Great","instructions":"test","status":"awesome","pricing_level":3,"longitude":"2.90873","latitude":"101 ...

Upgrade your angular/ionic app by swapping out inline data with a JSON service!

Could you assist in updating the current service with json data? The service currently has hardcoded information, and the corresponding controller is provided below. services.js angular.module('directory.services', []) .factory('Employe ...

angularjs error: $window.location.href is not defined

I am currently working on developing an application using ASP.NET MVC6, AngularJS, and Bootstrap. One of the challenges I am facing is reloading a page after closing a Bootstrap modal. However, when attempting to do so using $window.location.href, I am enc ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

How to Populate Object Literal with Multiple Objects in AngularJS

When I click on "Evan", I receive the following response: {"id":1,"name":"Evan"} If I click on "Robert", I will get: {"id":2,"name":"Robert"} Is there a way to modify this code so that it follows the aforementioned steps and generates an object similar ...

Exploring the depths of Master-Detail functionality with Ionic and Angular, unlocking nested

Hey there! I'm currently working on a project using Ionic and Angular, where users can view events and see all the attending participants along with their information. To achieve this, I implemented a master-detail pattern within another master-detail ...

The browser is failing to send cookies to the backend and is also not properly setting them initially

Greetings everyone, I am currently in the process of securing my spring boot application with HTTP only cookies, transitioning from local storage. However, I have encountered some challenges along the way that even chatGPT couldn't resolve :) Let&apo ...