The file you downloaded is corrupted due to an error in interpreting the JPEG image file. It seems that it is not a JPEG file as it starts with 0xef

Trying to download a file from our system using Spring Boot and AngularJS 1. The file downloads successfully but when trying to open it, an error message appears: Error interpreting JPEG image file (Not a JPEG file: starts with 0xef 0xbf). The sample code used is as follows:

DownloadService.java

import com.codahale.metrics.annotation.Timed;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.net.URLConnection;

@Component
@RequestMapping("/api/1/download")
@Path("/api/1/download")
@Consumes(MediaType.APPLICATION_JSON)
@Slf4j
public class DownloadResource {

 @ApiOperation(value = "downloads selected file", notes = "Returns a file", responseContainer = "FileSystemResource", response = HttpServletResponse.class)
 @Path("/downloadFile")
 @GET
 @Timed
 public void downloadFile(@Context HttpServletResponse response) throws IOException {
     // Code for downloading file goes here...
 }

}



download.js

// AngularJS controller for downloading the file

app.controller('storeReportsCtrl', function($rootScope, $scope, Restangular, $state, $stateParams, $location, $modal, $log, $timeout,$http,$sce) {
    $scope.download = function(fileName) {
        // Code for downloading file in AngularJS goes here...
    }
});

After downloading the file, it seems to be corrupted as the original file size is 18,394 bytes but the downloaded file has a byte length of 33,496.

UPDATE

The same code works fine for text files but not for binary files. Any suggestions on how to correctly download binary files?

Answer №1

Ensure that the file path is correct for accessing the CTA.jpg file on your system.

 @GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) throws IOException {
    String filePath = ("\\home\\ashish\\Desktop\\CTA.jpg");
    File fileName = new File(filePath);     
    String mimeType = URLConnection.guessContentTypeFromName(fileName.getName());
    System.out.println(mimeType);
    if (mimeType == null) {
        System.out.println("Mimetype cannot be detected, using default application/octet-stream.");
        mimeType = "application/octet-stream";
    }
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", String.format("inline; filename=\"" + fileName.getName() + "\""));
    response.setContentLength((int) fileName.length());
    InputStream inputStream;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(fileName));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
        inputStream.close();
    } catch (FileNotFoundException e) {
        // Handle file not found exception
        e.printStackTrace();
    }
}

If CTA.jpg is part of your resource path, you can access it like this:

 InputStream in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("CTA.png");

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 to stop Bootstrap collapsible items from "shifting"

I recently integrated a Bootstrap collapse plugin to manage my list of common inquiries: https://jsfiddle.net/2d8ytuq0/ <ul class="faq__questions"> <li> <a href="#" data-toggle="collapse" data-target="#faq__question_1">..</a> ...

Incorporate a form component in Vue2, utilizing an input type of textarea to both display and edit data without the need to manipulate props

Embarking on building an MVP for the first time in web development. Leveraging Vue2 and Firebase, progress has been smooth up until now. However, a roadblock has emerged that I am unable to navigate solo. Though the concept is clear in my mind, translatin ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Transforming a variable into a class using JavaScript and Node

Hey there, back with another question. I have a new variable in NodeJS called Blessed that looks like this: var box = blessed.box({ width: '100%', height: 1, content: someContent, tags: true, style: { fg: 'white', bg: ...

React Nextjs implementation of a fixed navigation bar to stick at the top

Hello, I am experiencing some issues setting up a sticky navbar in Next.js. The current navbar doesn't seem to be functioning as expected. Is there anyone who can assist me with the code provided below? import React, { useEffect } from 'react&apo ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

The radio button is displaying the text 'on' instead of its designated value

function perform_global(tablecounter) { for (index = 1; index <= 2; ++index) { var dnsname = "dns_name"+index; oRadio = document.getElementsByName(dnsname); alert (" radio ID " + dnsname + " " + index + "length " + oRadio.leng ...

Retrieve an array of the points currently displayed on the Chart.js graph

While utilizing Chart.js with zoom and pan capabilities, I am attempting to create a function that exports only the content visible on the canvas to a CSV file. However, I am struggling to identify how to retrieve solely the visible data points after user ...

Exploring the world of React and Material Ui

As I delve into working with Material Ui in React, I am encountering difficulties when trying to customize the components. For instance, let's take a look at an example of the AppBar: import React from 'react'; import AppBar from 'mat ...

Using the Node.js mongodb-native library to insert multiple strings as separate documents

node: 8.9.4 mongo: 3.6.3 mongodb-native: 2.2.33 Query: How can I seamlessly insert an array of simple strings as new documents with just one call? I prefer not to pre-process the array before insertion. I'm in search of a magical mongo solution h ...

Strategies for handling uncaught promise rejections within a Promise catch block

I'm facing a challenge with handling errors in Promise functions that use reject. I want to catch these errors in the catch block of the Promise.all() call, but it results in an "Unhandled promise rejection" error. function errorFunc() { return ne ...

How can I successfully transmit the entire event during the (change) event binding with ng-select in Angular 14?

I'm working on Front end Code <ng-select formControlName="constituencyId" placeholder="Select Constituency" (change)='onContituencyChanged($event)'> > &l ...

Transforming the Date into Local Time: An Instantaneous Process?

I am currently working with a Kendo UI MVC grid that contains three date columns. These dates, which do not include any time values, are stored in the database as local time rather than UTC. The columns within the grid are defined like so: col ...

Using cytoscape.js to implement a distinct color mapping for node background colors

I am currently learning Javascript and Cytoscape.JS, and I am attempting to implement a discrete color mapping for my nodes based on a specific property in my data. This property consists of five unique values (a, b, c, d, e), and I want to assign colors t ...

Prevent child div from resizing along with parent div during a resize event by utilizing the .resizable()

Check out this example here I am able to resize the div using jQuery, but I don't want the #spacer to have a fixed width at first because the content of the could vary in size. Even if I remove: width:100px; and try setting it to a percentage or ...

The Bootbox dialog.modal('hide') function is not effectively hiding the modal

I am facing an issue with bootbox.js modals. I am trying to utilize bootbox.dialog to pause the UI while an Ajax request is in progress and awaiting a response. Everything works fine when using dialog.modal('hide'); within bootbox.alert with conf ...

Having difficulty retrieving the element's identifier

I am facing an issue with the following directive, as I am attempting to retrieve the element and attribute id but it is returning undefined. Here is the code snippet: 'use strict'; angular.module('clientApp') .directive('myVid ...

I attempted to click on the search button by its class, but instead, another button with the same class name is being clicked. Why is it selecting the wrong button?

Search button html code. <button type="button" class="btn form-control customSelect dropdown-toggle" dropdown-toggle="" ng-disabled="disabled" aria-haspopup="true" aria-expanded="false"> <span class="cust ...

Adjust gaps automatically between vertical bars in chart.js

I am currently developing a webpage that showcases a dashboard based on an invoice processing project. With the code below, I am creating a bar chart for visualization: function loadVolumeChart() { var pieChartContent = document.getElementById('ch ...

Tips on merging several JavaScript files into a singular one while maintaining the operation of electron

Query: Is there a way to combine multiple JavaScript files into one file and obfuscate it, while still being able to execute it with Node.js Electron? Consideration: I am aware that all JavaScript files in an Electron project can be obfuscated and execu ...