使用angular2和spring下载文件

时间:2017-05-18 06:38:08

标签: java spring angular2-routing

我正在尝试使用spring代码下载文件,我的代码正在运行,但下载文件夹中没有下载文件。我的代码是: -

  @RequestMapping(value="/downloadRecordFile/{id}",
    method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public void downloadRecordFile(@PathVariable("id") Long id,HttpServletRequest request,HttpServletResponse response) throws IOException {


     File fileName = new  File("C:\workarea\UplodedRecords\test_annotation.pdf");
     if (fileName != null) {         
                if (!fileName.exists()) {
                String errorMessage = "Sorry. The file you are looking for does not exist";
                log.info(errorMessage);
                OutputStream outputStream = response.getOutputStream();
                outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
                outputStream.close();
                return;
            }

            String mimeType = URLConnection.guessContentTypeFromName(fileName.getName());
            if (mimeType == null) {                    
                mimeType = "application/octet-stream";
            }

            log.info("mimetype : " + mimeType);
            response.setContentType(mimeType);
            response.setHeader("Content-Disposition", String.format("inline; filename=\"" + fileName.getName() + "\""));
            response.setContentLength((int) fileName.length());
            InputStream inputStream = new BufferedInputStream(new FileInputStream(fileName));

            //Copy bytes from source to destination(outputstream in this example), closes both streams.
            FileCopyUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
            response.getOutputStream().flush();

        }
    }
}

我的代码不是givivng错误或异常,但它没有下载文件。

angular 2代码: -

function downloadRecord() {
        alert("Downloading");
        var record_id = 1234;
        downloadRecordFile.query({id: record_id}, onSuccess);
    }

这是我的服务js

(function() {
'use strict';

angular
    .module('testApp')
    .factory('downloadRecordFile', downloadRecordFile);

 downloadRecordFile.$inject = ['$resource'];

function downloadRecordFile($resource) {
    var resourceUrl = 'api/downloadRecordFile/:id';
  return $resource(resourceUrl, {}, {
              'query': { method: 'GET', isArray: true},
              'get': {
                  method: 'GET',
                  transformResponse: function (data) {
                      if (data) {
                          data = angular.fromJson(data);
                      }
                      return data;
                  }
              }
          });
      }
  })();

代码中是否有任何错误请帮助我。

0 个答案:

没有答案