Trouble with transferring ZIP file from servlet to client

Having trouble sending a zip file from a Java servlet to a JavaScript client. The zip archive is generated successfully on disk, but there's an issue with transferring it to the client.

The code snippet responsible for sending the file in the doPost method is as follows:

  String path = getServletContext().getRealPath("/") + "generatedApps/";     
  String fileName = appName + "Archive.zip";
  File f = new File(path + fileName);       

  response.setContentType("application/zip");     
  response.setContentLength((int)f.length());  
  response.addHeader("Content-Encoding", "gzip"); 
  response.addHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");    
  byte[] arBytes = new byte[(int)f.length()];     
  FileInputStream is = new FileInputStream(f);     
  is.read(arBytes);     
  ServletOutputStream op = response.getOutputStream();     
  op.write(arBytes);     
  op.flush();    

Here's the Ajax request made by the client:

new Ajax.Request( source, {
  asynchronous: false,
  method: 'post',
  parameters: {content: RWSMLFile},
  onSuccess: function(transport){                   
    console.log(transport);
  }.bind(this),
  onFailure: (function ( transport ) {
    ORYX.Log.error( "Sending RWSML file failed! Info: " + transport );
  }).bind( this )
} );

The browser console displays the following error message:

POST http://localhost:8080/oryx/generategeddyjscode  prototype-1.5.1.js:1044
  Ajax.Request.Object.extend.request prototype-1.5.1.js:1044
  Ajax.Request.Object.extend.initialize prototype-1.5.1.js:1006
  (anonymous function) prototype-1.5.1.js:37
  ORYX.Plugins.RWSMLSupport.ORYX.Plugins.AbstractPlugin.extend.generateGeddyJsCode rwsmlSupport.js:47
  (anonymous function) prototype-1.5.1.js:105
  a.each.j.functionality default.js:2828
  Ext.Button.Ext.extend.onClick ext-all.js:87
  V ext-all.js:13
  O

When checking the Source tab, I encounter a Failed to load resource message after the last line of the following code snippet:

  if (this.options.onCreate) this.options.onCreate(this.transport);
  Ajax.Responders.dispatch('onCreate', this, this.transport);

  this.transport.open(this.method.toUpperCase(), this.url,
    this.options.asynchronous);

  if (this.options.asynchronous)
    setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

  this.transport.onreadystatechange = this.onStateChange.bind(this);
  this.setRequestHeaders();

  this.body = this.method == 'post' ? (this.options.postBody || params) : null;
  this.transport.send(this.body);

Looking for guidance on resolving this issue. Any suggestions?

Answer №1

To determine the number of bytes that have been written, you can utilize the return value of FileInputStream.read(). Here is an example implementation:

  String path = getServletContext().getRealPath("/") + "generatedApps/";     
  String fileName = appName + "Archive.zip";
  File f = new File(path + fileName);       

  response.setContentType("application/zip");     
  response.setContentLength((int)f.length());  
  response.addHeader("Content-Disposition","attachment;filename=\"" + fileName + "\"");    
  byte[] arBytes = new byte[32768];     
  FileInputStream is = new FileInputStream(f);
  ServletOutputStream op = response.getOutputStream();     
  int count;
  while ((count = is.read(arBytes)) > 0)
  {
      op.write(arBytes, 0, count);     
  }
  op.flush();    

Edit:

The line

response.addHeader("Content-Encoding", "gzip");
, which was mentioned in the original question, has been removed as it was deemed incorrect.

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

What is the process for evaluating the variable `results` in this scenario?

Can anyone provide some insight on how this code is functioning? I grasp the concept of callbacks but during a tutorial video, I encountered this code snippet: function addAndHandle(n1, n2, cb) { const result = n1 + n2; cb(result); } addAndHandle ...

Tips for capturing the datePicker closing event

Currently, I have successfully implemented a date picker on my website. In some sections of my page, there is a requirement for calculating values based on the start and end dates selected by the user. However, I am facing an issue where I am unable to per ...

Using NextJS to fetch data from an API after a form submission

Struggling with integrating an API call in my NextJS application, specifically when submitting a form. I keep encountering a random error upon submission, Error: Search(...): Nothing was returned from render. This usually means a return statement is missin ...

The callback information is not being properly identified

I need help with deleting an entire row when the Delete button is clicked using jQuery. Here is my current approach: UPDATE: I have made final adjustments to the click function: $(document).on('click', '.delete-assignment',function () ...

Pass a data variable to an HTML file using express's sendfile function (quick inquiry)

Currently utilizing Node.JS, path, and express for running an HTML webpage. I need to pass a variable to the HTML file for its utilization: var client_cred_access_token = 'fakeToken'; ... app.get('/', function (req, res) { res.se ...

The useSelector from @reduxjs/toolkit in Next.js is returning an undefined value

Utilizing js and @reduxjs/toolkit in my current project has resulted in an issue where the useSelector method is returning undefined values when trying to access data from the store. Below is a snippet of my reducer file: import { createSlice } from "@red ...

Avoid using floats on the Y axis when working with VISX

Is there a way to prevent floating point numbers on the Y axis without using Math.round, as it disrupts the axis? Are there any features in VISX akin to CHART.js precision? https://i.sstatic.net/8x3Pn.png ...

Iterating through a JSON object and an array

I've been attempting to iterate through a JSON object but I'm struggling with it. Below is the JSON object I need to work with. This JSON data will be fetched from another website, and my goal is to loop through it to extract certain details. ...

"Effortlessly attach and send multiple images via email using Dropzone in

I am encountering an issue with uploading multiple image files and sending them via email to customers. The ajax request is throwing an error call to a member function getclientoriginalname() on array when the uploadMultiple: true, option is added to dropz ...

Styling paragraph elements using CSS in JavaScript

I need help applying CSS styling to a paragraph that is being extracted using JavaScript. Here's the current code I have: var info = "<p>" + meeting.summary + "</p>; I attempted to add some styling with the following cod ...

Tips for being patient while waiting for a function to return a value

I'm working on a React class and I'm facing an issue. The problem is that the variable isTokenActive is returning undefined, and I suspect it's because I need to wait for the function checkIfRefreshTokenWorking to return a value. componentD ...

Is there a way to capture the click event of a dynamically generated row within a panel?

Could you please advise on how to capture the click event of a row that is generated within a panel? I have successfully captured events for rows generated on a page using the , but now I need assistance with capturing events from rows within a panel. I c ...

Transform the jQuery UI Slider to be clickable rather than draggable

Currently using jQuery UI 1.10.3 and aiming to create a slider widget that is not draggable. The intention is for the user to click on specific values along the slider instead. I previously attempted using eventDefault in the slider's start method, b ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

calling an instance method from a static context

I find myself feeling a bit lost on this topic, and my exploration of the suggested solutions here has not led me to a quick resolution that fits my specific situation. My inquiry is rather straightforward. Let's imagine I have a method structured li ...

Significant slowdown observed when deleting multiple objects from the Three.js scene

We are facing a challenge when dealing with large Three.js scenes that consist of many individual objects. In some cases, our scenes can contain anywhere from 25,000 to 50,000 instances of Object3D. While this may seem like a lot, we haven't found an ...

Trouble retrieving data through AJAX request on Intel XDK

I am in the process of developing an APK for the blood bank in my local city. One of the key functionalities I'm working on is obtaining the stock of blood by groups. I have successfully tested some JSON data using Postman, but the challenge now is in ...

Sorting of array in AngularJS ngRepeat may result in changing the length of the array

Link to JSFiddle: http://jsfiddle.net/WdVDh/101/. When updating the sorting option for an ng-repeat list, I noticed that the array length changes and in my local version, all items disappear. My code involves filtering and sorting, with the ability to fi ...

Is a specific format necessary for express next(err) to function properly?

Recently, while working on my express sub app that utilizes the http-errors module, I encountered an interesting issue. When passing new Forbidden() to the next() callback, it seemed to vanish without triggering any callbacks. However, passing new Error() ...

What is the best way to embed a variable within a Directive HTML block for seamless access by the Controller?

I am facing a challenge with my custom directive that inserts an HTML block onto the page. The issue is to have a variable within this block that can be manipulated based on an ng-click function in my controller. This is what my directive looks like: .di ...