The file upload functionality is functioning properly when tested with Postman, however, it is encountering issues

I am currently facing an issue with file upload. I am using Angular in the front-end and Java in the backend to upload images to an S3 bucket. The Java code seems fine as I tested the upload URL on Postman and it worked smoothly. Here is a screenshot from Postman showcasing the successful upload:

https://i.sstatic.net/Ohe7V.png

Below is my AngularJS Controller:

contactUs.controller('contactController', ['$scope','$http', 
function($scope,$http) {    
    $scope.uploadFile = function(){
        var file = $scope.myFile;

           console.log('file is ' );
           console.dir(file);

           var uploadUrl = "uploadURL";

           var fd = new FormData(file);
           fd.append('files', file);

           $http.post(uploadUrl, fd, {
              transformRequest: angular.identity,
              headers: {'Content-Type': 'multipart/form-data',
                        'Authorization': 'Basic QHN0cmlrZXIwNzoxMjM0NTY='}
           })

           .success(function(response){
            console.log(response);
           })

           .error(function(error){
            console.log(error);
           });
        };
  }]);

Here is My AngularJS Directive as follows :

contactUs.directive('fileModel', ['$parse', function ($parse) {
        return {
           restrict: 'A',
           link: function(scope, element, attrs) {
              var model = $parse(attrs.fileModel);
              var modelSetter = model.assign;
              console.log(model);
              console.log(modelSetter);
              element.bind('change', function(){
                 scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                 });
              });
           }
        };
           }]);

The HTML is as follows :

<input type = "file" name="files" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>

The Java controller is as follows :

@Path("/upload")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/text")
public Response uploadFile(@FormDataParam("files") List<FormDataBodyPart> bodyParts,@FormDataParam("files") FormDataContentDisposition fileDispositions) {
    /* Save multiple files */
    BodyPartEntity bodyPartEntity = null;
    String fileName = null;
    for (int i = 0; i < bodyParts.size(); i++) {
        bodyPartEntity = (BodyPartEntity) bodyParts.get(i).getEntity();
        fileName = bodyParts.get(i).getContentDisposition().getFileName();
        s3Wrapper.upload(bodyPartEntity.getInputStream(), fileName);
    }
    String message= "File successfully uploaded !!";
    return Response.ok(message).build();
}

The Error I am encountering with AngularJS is shown below:

400 - Bad Request

Answer №1

1) When sending File data using the POST method, there is no need to specify the content-type as Multi part/form-data. The system can automatically determine the data type, so simply include

headers: {'Content-Type': undefined}
.

2) As seen in your Postman example, if the key is files, then make sure that you are not duplicating it by including name="files" and fd.append("files",file). This will cause a conflict with the key name on both ends. Therefore, remove name="files" from the HTML code before proceeding with the file upload.

Answer №2

When sending multi-part form data using $http, my go-to method is as follows:

const formData = new FormData();
formData.append('files', file);
return $http.post(uploadUrl, formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined} });

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

Tips for retrieving information using patterns and matchers

Hi, I am currently working on mapping old URLs to new ones. For example - /oldapp/viewReview.do?action=show_references&bugId=xy12&queueName=OLLD-CodeReviews to - newapp/review/reference?bugId=xy12&queueName=OLLD-CodeReviews I'm looking ...

Mismatched data types for function arguments

const x: Example = { toY: (y: Maple) => { return y.p; } }; interface Example { toY: (y: Pine) => void; } interface Pine { c: string; } interface Maple extends Pine { p: boolean; } Despite the warning for interface names ...

Sending a response with Express before an asynchronous function has completed

app.get('/test',(req,res)=>{ doSomething().then(res.sendFile(path,(err)=>{ if (err) { console.log('err') } else { console.log('Sent:', fileName) } })) asyn ...

Ways to modify or add styles to p tags using the Document Object Model (DOM)

I am trying to change the font size variable in my P tag using the DOM, but I am struggling to find a way to access it and modify the styles. I attempted the following code: document.body.p.style.font-size = ""+p_var+"px"; I have also tried using various ...

Struggling to transfer a specific row from a grid to a fresh window in extjs

My goal is to send the selected row from a grid panel to a new window when the user clicks the edit button or double-clicks the row. However, I am encountering difficulties in sending the data. Below is the code for my grid panel (List.js): Ext.define(&a ...

The Dynamic Chat System: Using AJAX with PHP and MySQL

Occasionally, my chat program experiences a rare issue where messages are displayed twice on the client side even though they are stored only once in the database. The chat system is implemented using AJAX, PHP, and MySQL. SELECT * FROM `ims` WHERE `to ...

Having trouble with the dropdown feature on AngularJs?

Encountering an issue while trying to display the dropdown list. Upon inspecting in Chrome, it seems like the data is loading correctly but when clicked, the dropdown menu does not show up. The data is fetched from the BooksController and all options are ...

What causes these queries to function separately but fail when combined?

I am facing an issue with combining 2 queries in my Firestore collection. These are the 2 examples that work: database .collection('servicebonnen') .where('medewerker', '==', 'CEES') and: database .collecti ...

A guide on retrieving an object and showcasing it in HTML using JavaScript

Can someone share a method to iterate through an object array in JavaScript? I have an array called sample where the property options needs to be displayed using lit-HTML for each object. var sample = [{ "trans": [{ "id": "trans", "fee": 20, ...

Setting the "status" of a queue: A step-by-step guide

I created a function to add a job to the queue with the following code: async addJob(someParameters: SomeParameters): Promise<void> { await this.saveToDb(someParameters); try { await this.jobQueue.add('job', ...

Encountering a JSON_PARSER_ERROR when trying to call Google FCM using MobileFirstAdapter JS

I am working on integrating Google FCM Api for sending Push Notifications. Below is the snippet of code from my JavaScript file: function sendNotificationToUser() { var request={ path :'/fcm/send', method: 'POST&ap ...

Best practices for removing css styles from a div element when selecting another within a Polymer application

Seeking assistance, can anyone help me? I have an iron-list with individual entries each containing a "settings" icon. When this icon is clicked, a panel slides in from the right. The issue I am facing is that I want the panel to close automatically when ...

When attempting to click the "New" button in a lightning datatable to add a new row, an error

Having trouble adding a new row when clicking the New Button in a Lightning Data table. I've created a lightning-button in HTML and called the method in JavaScript. However, when I click the New button, I'm getting an error message saying Undefin ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Encountering a SQL error in iBatis

select ID,NAME,SEX,RESIDENCE,EMAIL,MOBILE,PASSWORD,MOOD,BIRTHDAY,AVATAR,TYPE,MONEY from user where ID in (select USER2 as id from friend where USER1=#userId# ...

Integrating Laravel with Angular to create a powerful API connection

After creating an API in Laravel, one of the routes it responds to is: apiServices.factory('apiService', ['$resource', function($resource){ return $resource('api/categories', {}, { 'get': {method:'G ...

Looking to add a dynamic drop-down menu to my search bar, similar to Google search

Is there a way to create a dynamic drop-down list where, when a user enters the first letter of a country name, the list displays countries with names starting with that letter? It's similar to the functionality of a Google search bar. The country nam ...

The AJAX request is missing the 'Access-Control-Allow-Origin' header

I'm currently working with JQuery: $('#myDiv').load('myApp/url',function(){ }); However, I'm encountering an issue where both Chrome and Firefox are displaying the error message "No 'Access-Control-Allow-Origin' he ...

What is the method for printing background images/styles without adjusting the browser's page setup?

Is there a method to maintain row striping in the printout like it appears on screen? <div id="test" style="background:#000000; color:#FFFFFF">Black Stripe</div> I would like to create a page with consistent row stripe formatting for printing ...

Guide on ensuring all dynamic components of a NodeJS SailsJS web application are loaded using ajax requests

Exploring SailsJS and NodeJS for the first time, I decided to dive into a tutorial on creating a basic web application using these technologies. My main query is regarding rendering views (excluding the template) through Ajax. I aim to achieve a similar f ...