Tips on utilizing AngularJS $http for transferring multipart/form-data

In the process of creating a visual interface that interfaces with various REST services (coded in Java), I am encountering an issue when attempting to call one such service:

@PUT
@Path("serviceName")
public Response serviceName(final FormDataMultiPart multiPart) {
......}

To call the service, I have implemented the following code:

service: function (data) {

            return $http({
                url: PATH_REST_SERVICES + '/serviceName',
                headers: {"Content-Type": "multipart/form-data"},
                data: data,
                method: "PUT"
            });
        }

However, upon making the request from my AngularJS service file, I receive error code 400 (bad request) if the service has Content-Type as multipart/form-data.

Alternatively, if the service is set to Content-Types like "application/x-www-form-urlencoded; charset=utf-8" or "application/json; charset=utf-8" or "application/form-data", I encounter a 415 (unsupported media type) error.

As I develop the front-end using JavaScript and HTML5, existing resources online do not address my specific issue as the FormDataMultiPart object doesn't have a Javascript equivalent.

I've attempted to format the data in multiple ways for transmission, consistently resulting in errors 400 or 415.

What would be the correct way to format the data for transmitting in this REST call?

Also, how should the Content-Type field in the headers be configured?

Answer №1

Using AngularJS $http for Sending FormData

The FormData interface offers a simple way to create key/value pairs representing form fields and their values, which can be easily transmitted using the XHR Send method. It follows a format similar to a form with the encoding type set to multipart/form-data.

var formData = new FormData();

formData.append('type', type);
formData.append('description', description);
formData.append('photo', photo); 

return $http({
    url: PATH_REST_SERVICES + '/serviceName',
    headers: {"Content-Type": undefined },
    data: formData,
    method: "PUT"
});

Ensure that the content type header is set to undefined. By default, the $http service sets the content type as application/json. Setting it to undefined will prompt the XHR API to automatically assign the content type as multipart/form-data with the appropriate multi-part boundary.

Answer №2

When working in Java, the necessary code for file upload looks like this:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
    @FormDataParam("file") InputStream uploadedInputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail) {

If you need more guidance, you can check out the example and link provided below:

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

How can a Vue component interact with a JavaScript method?

Within my main.js file, I have configured Vue as follows: window.Vue = require('vue'); Vue.component('my-component', require('./components/MyComponent.vue')); const app = new Vue({ el: '#app', }); Additionall ...

Tips for accessing the parent method within a jQuery AJAX success function

Similar Question: javascript how to reference parent element Hello everyone! This is my first time posting here. I have a question - how can I trigger alerts from a successful AJAX call? var page = { alerts: function (json) { if (json ...

Retrieving information from controller to HTML page in AngularJS

Check out my code on Plunkr: http://plnkr.co/edit/8sBafktFzFa8fCLLJgMF This is the JavaScript file: angular.module('ui.bootstrap.demo', ['ui.bootstrap']); angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl&ap ...

How to Redirect Multiple URLs Simultaneously using Laravel

Upon clicking a button, the user will be redirected to generate a PDF in a new tab and simultaneously redirected back to the dashboard as well. ...

What is the best way to incorporate a text box along with a submit button that triggers a callback to a javascript function when clicked, utilizing either plain javascript or jQuery?

As a beginner in the world of JavaScript, I'm struggling to find the solution to this problem. Any assistance would be greatly welcomed. ...

Steps for loading a directive into a module after instantiation with requirejs

Let me share a bit about my current challenge. Initially, I had all the necessary directive files injected into my main module in app.js using requirejs paths, and everything was functioning smoothly. It looked something like this: define(['angularAM ...

Tips for getting the setInterval function to work with a progress bar even when a tab is not in focus

After browsing through similar questions, I couldn't find the answer I was looking for. As a newbie in programming experimenting with JavaScript Progress Bar, I encountered an issue where the progress bar would pause and the counter wouldn't coun ...

Unable to process a JSON response received from RestTemplate

While attempting to parse a JSON response from a web service, I encountered an error message stating that the request sent by the client was syntactically incorrect. Despite my efforts to troubleshoot and remove the Results class from the code, the issue p ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...

sending information to PHP through AJAX dynamically

I implemented a registration form that utilizes function user_reg(user_name,user_email,user_pswd) { var serverpath=window.location; alert(serverpath); var dataString = 'name='+ user_name + '&email=' + user_email + '&psw ...

Encountering issues with generating image files using createObjectURL after transitioning to NextJS 13 from version 10

I'm currently working on a website with the following functionality: Client side: making an API call to retrieve an image from a URL Server side: fetching the image data by URL and returning it as an arrayBuffer Client side: extracting the arrayBuffe ...

What specific URL should be included in a JavaScript ajax request?

As I delve into creating a JSON file using an ajax request in javascript, confusion strikes when it comes to determining the appropriate URL. With no previous experience working server side and relying on WAMP server 3.0.6 to host my project-in-the-works ...

Printing HTML to a VueJS page is simple and efficient

I have a situation where one of my attributes in a property contains an HTML string. Instead of rendering the HTML as expected, when I output it within my template, the browser displays the raw HTML code with tags intact. It doesn't interpret it as a ...

Encountering error message "Module not found '@angular/compiler-cli/ngcc'" while attempting to run "ng serve" for my application

Encountering an error while trying to run my app, I have attempted various solutions available online. These include uninstalling and reinstalling angular/cli, verifying the correct version in package.json (ensuring it is "@angular/cli" and not "@angular-c ...

Can you provide guidance on extracting keys and values from a JSON object in Java?

After successfully extracting data from a website, I received the following response: {"vulnerability":{"id":15017916,"status":"open","closed_at":null,"created_at":"2019-07-26T10:06:03Z","due_date":null,"notes":null,"port":[],"priority":null,"identifiers" ...

Utilizing cylon.js with Nest Thermostat

Experiencing errors while trying to retrieve thermostat ambient Temperature with cylon.js I have already replaced ACCESS_TOKEN with my unique access token and device id Sample Code: var Cylon = require('cylon'); Cylon.robot({ connections: { ...

Using jQuery, learn how to successfully call a selector from dynamic content

I am currently facing a challenge with a table that is generated server-side and then appended to the view page (client-side). Since the table is not directly included in the DOM, I am using the StickyTableHeaders jQuery plugin to create a sticky header fo ...

Redirecting pages using an Ajax script in JavaScript

Unfortunately, I am unable to use a *.php extension for my page due to unforeseen circumstances. This has led me to consider using *.html instead and implementing conditional redirection using javascript/Ajax to call a PHP script that can evaluate the cond ...

My program contains redundant sections that are being repeated multiple times, and I am unsure of how to remedy this issue

This particular payment gateway relies on a paid market for processing transactions. Unfortunately, there seems to be an issue where multiple error messages are being triggered during the payment verification process. The errors include: ❌ | An error h ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...