首页 > 用responseEntity返回文件给前端,但是前端不弹出下载,反而reponse是乱码

用responseEntity返回文件给前端,但是前端不弹出下载,反而reponse是乱码

代码:

    @RequestMapping(value = "/toExportData.req", method = RequestMethod.POST)
    public ResponseEntity<byte[]> exportRequest(@RequestParam("array") String arr) {


        

        ResponseEntity<byte[]> responseEntity = null;

//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        byte[] body = null;
        InputStream is = null;
        try {
//            createExcelFile().write(os);
//            body = os.toByteArray();

//            body = FileUtils.readFileToByteArray(new File("E:/export.xlsx"));

            String filePath = "E:/export.xlsx";
            File file = new File(filePath);
            byte[] bytes = FileUtils.readFileToByteArray(file);

            System.out.println("读取 输入流.....");
            HttpHeaders headers = new HttpHeaders();
            HttpStatus httpStatus = HttpStatus.OK;

            System.out.println("设置headers。。。。");

            headers.add("Content-Disposition", "attachment;filename=export.xlsx");
            headers.setContentType(MediaType.valueOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));

            System.out.println("headers is: " + headers);

            responseEntity = new ResponseEntity<byte[]>(bytes, headers, httpStatus);

            System.out.println("responseEntity:" + responseEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseEntity;
    }

前端接受:

    exportDataRequst: function (array) {
            /**   上传的方法  **/

            var args = {"array": array};
            var url = "toExportData.req";

            return $http({
                method: 'POST',
                data: args,
                url: url
            }).success(function (response) {

                return response;

            }).error(function (response, status) {

上面的response返回的就是一堆乱码。那段后端的代码,在单纯用超链接请求的时候,是可以自动下载文件的。但是这里用了angular的请求,就不知道为啥了,没法弹出下载,还乱码

【热门文章】
【热门文章】