What is the process for uploading a file with POST in angular?

What is the best way to send a pdf file without completely revamping our current system? I have explored various methods online, but most of them involve significant changes to our architecture, which is not ideal.

Although I am not very experienced with angular, I am attempting to upload a file to the server using the existing framework. When I try to send it as a multipart file, Spring throws an error stating that "The current request is not a multipart request." I am unsure how to convert it to a multipart request or ensure the file type is a Blob. Currently, no error is thrown, but the data.content field appears empty after the transmission.

This is the current code snippet in question:

$scope.uploadPDF = function(uploadedPDF) {
    var url = 'uploadPDF';
    data = {};
    data.comments = $scope.worksheet.comments;
    data.queryId = $scope.qId;
    data.responseId = $scope.responseId;
    data.requestTS = new Date().getTime();
    data.content = uploadedPDF;
    $http.post(url, data);
};

The calling function retrieves the file, generates a unique name for it, performs some unrelated logic, and then invokes the transmission function:

$scope.addPDF = function() {

 var pdfUploads = document.getElementById('file');
  if ('files' in pdfUploads)
  {
    if (pdfUploads.files.length == 0)
    {
        $scope.setReasonForChange("addPDF");
    }else
    {
        for (var i = 0; i < pdfUploads.files.length; i++)
        {
           var currentTimeZone = new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2];
           $scope.militaryTime = $filter('date')(Date.now(), "MM-dd-yyyy_HHmm");
           pdfUploads.files[i].generatedFileName = "QID-" + $scope.queryId + "_" + $scope.worksheet.response.PDF_DESCRIPTION + "_" + $scope.militaryTime + currentTimeZone + ".PDF";
        }
    }
} 

    var pdfComment = document.getElementById("pdfComment").value;
    if (!pdfComment)
    {
        $scope.setReasonForChange("updatePDF");

    } else
    {
        var blobPDF = new Blob([pdfUploads.files[0]], {type: 'application/pdf'});
        $scope.uploadPDF(blobPDF);
    }
}

The HTML form for file upload is as follows:

<form name="UploadForm" id="UploadForm" class="details" form-on-change="formChanged()" enctype="multipart/form-data">
            <input type="file" multiple size="50" id="file" name="file" ng-disabled="is_readonly"/>
            <button ng-click="addPDF()" ng-disabled="is_readonly">Add</button>
</form>

Regarding the server-side code, the data is part of a linked hashmap, and the values are extracted and processed on the server:

@ResponseBody
@RequestMapping(value = "/uploadPDF", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseAttachment uploadPDF(@RequestBody Data data, HttpServletRequest request) throws Exception {
    User user = (user) request.getSession(false).getAttribute(FieldConstants.USER_SESSION_ATTR);
    ResponseAttachment newPDF = responseAttachmentService.addAttachment(data, user.getUserId());

    return newPDF;

The data transmission works, but the file field remains empty in the designated location.

I have experimented with ng-fileupload, but integrating it into our system is challenging, especially since it assumes a certain level of familiarity with angular, which we currently lack.

Answer №1

Check out this question for a solution.

Essentially, sending files in a JSON format is not possible. You must use a multipart form to properly post it. Here's an example:

postFile(file) {
    var postData = new FormData();
    postData.append('File', file);

    var params = {
    headers: {
        "Content-Type": undefined
    }

    $http.post(url, data, params).then([...]);
}

Make sure to include the additional Content-Type parameter for proper sending.

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

Leveraging jQuery to manipulate an SVG file

jQuery is designed to work within HTML pages that contain JavaScript code. While SVG and HTML both use the same DOM Level 2, SVG is XML-based and employs ECMAScript. What potential issues could arise from utilizing jQuery with SVG? Is it more advisable t ...

I'm looking to extract various data from a SQLite table using the URL with ExpressJS. What's the best way to achieve

I need to access data from a SQLite database table that contains information on accounts, movies, and reviews. Specifically, the structure of the reviews-table is as follows: CREATE TABLE IF NOT EXISTS reviews ( id INTEGER PRIMARY KEY, authorId INT ...

Dynamic blog posts experiencing issues with syntax highlighting feature

I am currently developing a blog using Vue and have decided to incorporate syntax highlighting for the code snippets in my posts by utilizing vue-highlightjs. In order to write the content of my blog posts, I am simply using a textarea within my admin pane ...

Uploading Files Using CodeIgniter's User Class

I am in a bit of a bind. I have a User Class that includes an edit_profile() function, and I would like to enable users to upload their photo while editing their profile. The issue is, when the form is submitted, it remains on the edit profile page utilizi ...

Is it possible to dynamically evaluate the fs argument?

When I tried to run npm run dev, I encountered the following error: An error occurred while attempting to evaluate the fs argument statically [0] 50 | // Read file and split into lines [0] 51 | var map = {}, [0] > 52 | content = fs.read ...

Exploring the process of navigating through jQuery Arrays: Utilizing JQuery Array Filter

I need help finding a way to SEARCH through a jQuery array or object. I'm not looking to just check if the value is in the array, but to search for related terms based on user input. It's similar to how we filter ArrayList in Java or use SQL LIKE ...

Postgres.js Date Range query failing to fetch any results

Recently, I have been utilizing the Postgres.js npm module to interact with a PostgreSQL database Below is the code snippet for executing the query: let startDate = '2020-01-28 08:39:00'; let endDate = '2020-01-28 08:39:59'; let table ...

Limiting character count in jQuery using JSON

I am trying to manipulate the output of a snippet of code in my jQuery: <li> Speed MPH: ' + val.speed_mph + '</li>\ that is being pulled from a JSON endpoint and currently displays as: Speed MPH: 7.671862999999999 Is there a ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

Alert! Server node encountered an issue while handling the response: process.nextTick(function(){throw err;});

Currently, I am working on a simple application to familiarize myself with Mongo, Express, and Node. An issue arises when I attempt to utilize res.json(docs) in the success conditional during the GET request, generating an error process.nextTick(function( ...

Utilizing Express Session with Vue CLI in a Node.js Environment

Developing a nodejs backend for my Vue application has brought up a challenge regarding user sessions and database operations. I initially tried using express-session, but the sessions appeared as undefined in subsequent requests. How can I address this is ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

The useEffect() method used without any cleanup function

It is mentioned that, "Every time our component renders, the effect is triggered, resulting in another event listener being added. With repeated clicks and re-renders, numerous event listeners are attached to the DOM! It is crucial to clean up after oursel ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

Encountering a snag when trying to execute the code in Selenium that pertains to launching a Chrome browser

Issue: Error encountered while attempting to launch the Chrome browser using Selenium WebDriver. The error message is as follows: Exception in thread "main" java.lang.NoClassDefFoundError: dev/failsafe/Policy at org.seleniumhq.selenium.http/org.openqa. ...

What is the best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

sending properties to dynamically loaded components

I'm struggling with transferring props between children and parent components using Vue Routes. Within my Layout component, I have a wrapper DIV structured like this: <template> <div class="container" v-bind:class="cssClass ...

Utilizing HTTP POST method in vanilla JavaScript with AJAX

Having some trouble sending a post request to my PHP file as it keeps saying 'undefined index'. Here is my JavaScript code: document.getElementById("btn1").addEventListener('click', xh ); function xh(){ xhr = new XMLHttp ...

What causes delayed state updates in React/NextJS until another state is updated or a fast refresh occurs?

UPDATE: Version 13.3.0 is coming soon! In my code, I have a state variable named localArray that I need to update at a specific index. To achieve this, I decided to create a temporary array to make modifications and then set the state with the updated val ...