在 jhipster 应用程序中将 .docx 文件从服务器发送到客户端

Send .docx file from server to client in jhipster application

我正在使用 Jhipster。

我正在使用 docx4j 创建 .docx 文件。

我想将此 .docx 文件从服务器下载到客户端。

但是我下载的文件已损坏。

在服务器端:

我生成我的文件并将其放入字节[]

WordprocessingMLPackage p = null;
...
File f = new File(filePath);
p.save(f);
byte[] stream = Files.readAllBytes(f.toPath());

我试过以不同的格式发送给客户:

字节[]

byte[]编码的Base64

字符串

字符串编码的 Base64

我的方法的示例:

// send back as String encoded in Base64
public ResponseEntity<FileDTO> getFile(@PathVariable Long id) throws URISyntaxException, IOException {
    FileDTO result = fillRepository.findOne(id);
    byte[] stream = FileUtil.getFile(id) // retrieve file as byte[]
    byte[] encoded = Base64.encodeBase64(stream);
    String encodedString = new String(encoded, "UTF-8");
    result.setFile(encodedString);
    return ResponseUtil.wrapOrNotFound(Optional.ofNullable(result));
}

在客户端:

我以 byte[] 或 String 形式检索我的文件,并将其放入 blob 中以供下载。

FileService.get({id: id}, function(result) {
    var res = result.file;
    // var res = Base64.decode(result.file);
    vm.blob = new Blob([res], {type: 'data:attachment;charset=utf-8;application/vnd.openxmlformats-officedocument.wordprocessingml.document'});
    vm.url = (window.URL || window.webkitURL).createObjectURL(vm.blob);
});

我的服务是这样声明的:

(function() {
    'use strict';
    angular
        .module('myApp')
        .factory('FileService', FileService);
    FileService.$inject = ['$resource', 'DateUtils'];
    function FileService($resource, DateUtils) {
        var resourceUrl =  'api/file/:id/generate';
        return $resource(resourceUrl, {}, {
            'get': {
                method: 'GET',
                responseType:'arraybuffer'
}});}})();

当我下载文件时说:

"We're sorry. We can't open file.docx because we found a problem with its content."

当我比较原始文件和在记事本++中下载的文件时,我发现二进制内容并不完全相同,就像 encode/decode 问题...

大小也不一样:

原文件13Ko

已下载文件 18Ko

你能帮我知道下载的文件损坏的原因和原因吗?

我终于找到了解决办法:

我在响应中直接发回了二进制文件,没有进行任何转换。 并使用 window.location

访问它

我是一个没有注释的新 Rest 控制器:@RequestMapping("/api")

@RestController
public class FileGenerationResource {
    ...
    @GetMapping("/file/{id}")
    @Timed
    public void getFile(@PathVariable Long id, HttpServletResponse response) throws URISyntaxException, IOException {
        FileInputStream stream = fileService.getFile(id);
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-disposition", "attachment; filename=test.docx");
        IOUtils.copy(stream,response.getOutputStream());
        stream.close();
    }
}

控制器内容:

(function() {
    'use strict';

    angular
        .module('myApp')
        .controller('MyController', MyController);

    MyController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance'];

    function MyController ($timeout, $scope, $stateParams, $uibModalInstance) {
        var vm = this;
        vm.clear = clear;
        vm.dwl = dwl;

        function dwl (id) {
            window.location = "http://localhost:8080/file/"+id;
            vm.clear();
        }

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }
    }
})();