Issue with uploading an Excel file via REST: The POI library refuses the file due to a problem with the

I am facing an issue while attempting to upload an excel (.xlsx) file using AngularJS and REST (Jersey). The multipart boundary is being added to the file received in REST, causing the apache POI Library to reject it as an invalid file with the following exception. Is there a solution to this problem?

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:39)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:254)
    at com.bt.ngwfmt.framework.rest.FileUploadHandler.fileUpload(FileUploadHandler.java:128)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    Truncated. see log file for complete stacktrace
Caused By: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
    at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:203)
    at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:673)
    at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:274)
    at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:254)
    Truncated. see log file for complete stacktrace 



    When I add @FormDataParam instead of @RequestParam I get the following   exception

    java.lang.NullPointerException
at   com.sun.jersey.multipart.impl.MultiPartReaderClientSide.unquoteMediaTypeParamete rs(MultiPartReaderClientSide.java:245)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readMultiPart(MultiPartReaderClientSide.java:172)
at com.sun.jersey.multipart.impl.MultiPartReaderServerSide.readMultiPart(MultiPartReaderServerSide.java:80)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:158)
at com.sun.jersey.multipart.impl.MultiPartReaderClientSide.readFrom(MultiPartReaderClientSide.java:85)

The inputstream with boundary can be found https://i.sstatic.net/8Sk2B.jpg

Java Snippet:

@POST
@Path("/uploadFile")

@Consumes(MediaType.MULTIPART_FORM_DATA)

@NoCache
public String fileUpload(@RequestParam("file") InputStream inputStream) {

    XSSFWorkbook myWorkBook = null;

    XSSFSheet mySheet;
    
    try {
        myWorkBook = new XSSFWorkbook(inputStream); //The exception is thrown at this line)
    } catch (IOException e) {
        logger.error("Can't open workbook", e);
        e.printStackTrace();
    }

.....

Angular snippet:

    angular.module(appName).controller('fileUploadController',
    [ '$scope', 'fileUpload', function($scope, fileUpload) {

        $scope.uploadFile = function() {
            var file = $scope.myFile;
            console.log('file is ');
            console.dir(file);
            var uploadUrl = "myurl";
            fileUpload.uploadFileToUrl(file, uploadUrl);
        };

    } ]);

angular.module(appName).directive('fileModel', [ '$parse', function($parse) {
return {
    restrict : 'A',
    link : function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function() {
            scope.$apply(function() {
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};
} ]);

angular
    .module(appName)
    .service(
            'fileUpload',
            [
                    '$http',
                    function($http) {
                        this.uploadFileToUrl = function(file, uploadUrl) {
                            var fd = new FormData();
                            //
                            fd.append('file', file);
                            $http
                                    .post(
                                            uploadUrl,
                                            fd,
                                            {
                                                transformRequest :     angular.identity,
                                                headers : {
                                                    'Content-Type' : "multipart/form-data" //"multipart/form-data"
                                                }
                                            }).success(function() {
                                    }).error(function() {
                                    });
                        }
                    } ]);

This issue is somewhat similar to one discussed in the following link, though specific to C#.

Answer №1

For proper file handling, it is recommended to use the FormDataParam annotation instead of RequestParam. Should the error persist, confirm that the file is being received by saving it to a temporary location. This issue typically occurs when the file content is empty, which seems to be the case in your situation.

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

Determine whether an image is retina or non-retina using just one picture

Is it possible to use just one picture that is already optimized for retina displays, but automatically resize or crop down to a non-retina version when viewed on a non-retina screen? I'm facing this issue specifically with IE while using a PC. The im ...

Using Vue to bind a class attribute with multiple Tailwind classes

I am attempting to associate an attribute and multiple tailwind classes with an HTML element. This is specifically for a tab menu where the goal is to dynamically display the title of the "active" tab and apply additional tailwind classes to modify the app ...

Generating Date Instances and Comparing Dates

I am struggling with converting and comparing dates extracted from a calendar to the current date. In Eclipse, there is a red line under my if statement. My objective is to compare the current date with the dates in the cells and then select/click the butt ...

variable identifier looping through elements

I'm attempting to assign a dynamic ID to my div using ng-repeat. Here's an example: <div id="$index" ng-repeat="repeat in results.myJsonResults"> <div id="$index" ng-click="saveID($index)" ng-repeat="subRepeat in results.myJsonResul ...

Activating text wrapping functionality

My current project involves converting HTML to PDF using jsPDF. In order to ensure that every word appears in the exact location as it does in the original HTML, I decided to wrap each word in <span> tags. Specifically, I have a font tag (not added b ...

The SQL query is not producing the desired results as anticipated

I developed a PHP REST API that includes a function to retrieve services based on a specific idpro or idclient. function getServices($request) { require_once 'db.php'; $emp = json_decode($request->getBody()); $id = $request-&g ...

What makes the ng-file-upload Upload service so special?

Why do I need to use the Upload service with ng-file-upload in this specific way? Upload.upload({ url: '/postMyFormHere', data: { fileToUpload: model.file, someField1: model.field1, someField2: model.field2, ...

What methods can be used to protect (encrypt using Java code) the information in a login form before it is sent to a servlet for

One major concern I have involves sending encrypted data (encrypted before sending the request) to a servlet. I attempted to call a function that encrypts passwords as an example, but I encountered difficulty passing values from JavaScript to Java code in ...

An error occurred when trying to load JSON data from Jinja2, and it was due to an unexpected number causing

Currently, I am in the process of developing a website using the Google app-engine. My goal is to showcase a table from a Google SQL database on this site. To achieve this, I am passing data from the database (.py) to the HTML file using Jinja2. However, ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

Filtering a nested array based on the value of an element's field in

I am trying to filter a nested array based on the value of an element field. The array that needs to be filtered is shown below. I want to filter by the checked value of each element. If the value is true, I want to keep the element; if false, discard it. ...

Use the `document.getElementsByClassName` method to retrieve elements with a specific class name and then insert content between

Is it possible to select the only post with a 'selected' class and then insert a div inside or between other divs? I am currently uploading images to my website's timeline and now I am attempting to group multiple images posted on the same d ...

Is there a way for me to figure out the specific log configuration source that Logback has utilized?

When utilizing log4j, the log4j.debug property can be used to identify which configuration file was utilized to configure the logging system. However, I have not been able to find a similar feature in the Logback logging framework. Is there a way to deter ...

Hough transformation in JavaScript with Node.js

Attempting to implement a 1-dimensional version of the Hough transform, focusing on optimizing for reduced dimensions based on minor properties. Included is the code and sample image with input and output visuals. Questioning what could be going wrong in ...

Configuring timezone for 'date' type in Plotly.js

I'm currently working on a graph to showcase the trend over time. The data I have is in Unix format and I use JavaScript code (new Date(data)).toUTCString to display it in my title. Surprisingly, while the data for the graph and the title is the same, ...

Execute an Android activity from the JNI directly within a C++ process without involving the Java side

In my current project, I am utilizing Eclipse to develop an Android application that involves both Java coding and jni C++ code. I am currently experimenting with starting a Java activity directly from the jni without any modifications to the Java side. I ...

What is the correct way to utilize href in CSS content property?

Below is the content of a box I have: https://i.sstatic.net/QmG5i.png When the above box is hovered over, it flips to this: https://i.sstatic.net/QsS9t.png This block's HTML code is as follows: <div class='tiles'> <div class= ...

Angular allows me to use the $http.get method to retrieve the HTML content of my index

This strange issue has been plaguing me - I apologize in advance for the lengthy code, but I believe it's necessary for you to understand my problem. Here is what I have in my index.html: <!DOCTYPE html> <html ng-app="mainApp"><!--Boot ...

Using Axios to Integrate an API - Displaying a Username and Password Pop-up

I have been given a project that involves API integration. I have successfully retrieved data from the API, but there is a pop-up appearing asking for a username and password. Although I have these credentials, I would like to log in without that pop-up ap ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...