1. 程式人生 > >spring-boot二進位制檔案下載

spring-boot二進位制檔案下載

小編最近在Web專案中,需要完成一個excel檔案匯入和匯出的功能。匯入沒有什麼問題,但是匯出折騰了小編半天時間。spring-boot在這裡有個坑,誰踩誰知道啊!不說廢話,先看spring-boot下載功能的實現程式碼。為了程式碼複用,我將上傳和下載對應的功能,放在了一個抽象的Controller類中,需要該功能的controller可以直接整合這個類,並且實現兩個abstract的方法即可。

    abstract public class UploadAndDownloadController {

    private Logger logger = LoggerFactory.getLogger(UploadAndDownloadController.class);

    /**
     * Download response entity.
     *
     * @param
id the id * @return the response entity */
@RequestMapping(value = "/download", method = RequestMethod.GET) @ResponseBody public ResponseEntity<byte[]> download(@RequestParam(value = "id", required = false) List<String> id) { File file = generate(parseId(id)); try
{ return ControllerUtil.createBytesResponse("download.xls", file); } catch (Exception e) { logger.error("檔案下載失敗", e); return null; } finally { file.delete(); } } /** * Upload response entity. * * @param file the file * @return
the response entity */
@RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public ResponseEntity<JSONObject> upload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { introduce(file.getInputStream()); } catch (Exception e) { logger.error("檔案匯入失敗", e); return ControllerUtil.createFileUploadFailureResponse("檔案匯入失敗"); } } return ControllerUtil.createFileUploadSuccessResponse(); } /** * Generate file. * * @param id the id * @return the file */ protected abstract File generate(List<Long> id); /** * Introduce. * * @param in the in */ protected abstract void introduce(InputStream in); protected abstract File getTemplateFile() throws IOException; private List<Long> parseId(List<String> id) { if (id == null) { return null; } return id.stream().filter(s -> { try { Long.parseLong(s); } catch (Exception e) { return false; } return true; }).map(Long::parseLong).collect(Collectors.toList()); } }

接下來,才是最重要的一步,沒有下面的設定,上面的下載功能就是廢的,下載下來的二進位制檔案全是亂碼。請看下面的程式碼。下面的程式碼擴充套件了WebMvcConfigurerAdapter,並添加了基於位元組的http訊息轉換器(預設只有基於字元的http訊息轉換器,所以如果不加這個,下載後的二進位制檔案全是亂碼)。

@Configuration
public class CustomWebAppConfigurer extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //此處是重點啊,親們
        converters.add(new ByteArrayHttpMessageConverter());
        super.configureMessageConverters(converters);
    }
}