SpringBoot Downloads Excel Files to Solve File Damage

Keywords: SpringBoot Excel Maven encoding

Recently, in making a module of springboot to download excel files, the downloaded files have been damaged all the time. A lot of solutions can't be found on the internet. The ink has been solved for half a day. The main reason is that the files in springboot's resource directory are automatically compressed by default. All direct downloads and opening errors occur. Here is a record of the solutions.

First up code

public void downloadExcel(HttpServletResponse response,HttpServletRequest request) {
        try {
            //Get the template name to download
            String fileName = "ruleConfig.xlsx";//ruleConfig.xlsx
            //Set the name of the file to download
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            //MIME Type of Notification Customer Service Document
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //The path to get the file
            String filePath = getClass().getResource("/static/" + fileName).getPath();
            System.out.println(filePath);
            FileInputStream input = new FileInputStream(filePath.substring(1));
            OutputStream out = response.getOutputStream();

           byte[] b = new byte[2048];
            int len;
            while ((len = input.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            input.close();
        } catch (Exception ex) {
            log.error("getApplicationTemplate :", ex);
            //Re Response.ok ("Application Import Template Download Failed! "";
        }
    }

This is the normal download code.

Solution

The point is to add plug-ins to pom to avoid compression

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<version>2.6</version>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
					<nonFilteredFileExtensions>
						<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
					</nonFilteredFileExtensions>
				</configuration>
			</plugin>

This plug-in prevents xlsx files from being automatically compressed in the resource directory, so that they can be downloaded and opened properly.

Posted by lyasian on Sat, 05 Oct 2019 05:53:46 -0700