Spring - download response as a file

前端 未结 7 734
無奈伤痛
無奈伤痛 2020-12-08 07:19

I am writing application using AngularJS and Spring. I would like to send request to the server and download response returned from controller as a file. In controller I hav

7条回答
  •  感动是毒
    2020-12-08 07:39

    It's working for me :

    • Spring controller : DownloadController.java

      package com.mycompany.myapp.controller;
      
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.OutputStream;
      
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import org.apache.commons.io.IOUtils;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.http.HttpStatus;
      import org.springframework.http.ResponseEntity;
      import org.springframework.web.bind.annotation.ExceptionHandler;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      import org.springframework.web.bind.annotation.RequestParam;
      import org.springframework.web.bind.annotation.RestController;
      
      import com.mycompany.myapp.exception.TechnicalException;
      
      
      @RestController
      public class DownloadController {
      
          private final Logger log = LoggerFactory.getLogger(DownloadController.class);
      
          @RequestMapping(value = "/download", method = RequestMethod.GET)
          public void download(@RequestParam ("name") String name, final HttpServletRequest request, final HttpServletResponse response) throws TechnicalException {
              log.trace("name : {}", name);
      
              File file = new File ("src/main/resources/" + name);
              log.trace("Write response...");
              try (InputStream fileInputStream = new FileInputStream(file);
                      OutputStream output = response.getOutputStream();) {
      
                  response.reset();
      
                  response.setContentType("application/octet-stream");
                  response.setContentLength((int) (file.length()));
      
                  response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
      
                  IOUtils.copyLarge(fileInputStream, output);
                  output.flush();
              } catch (IOException e) {
                  log.error(e.getMessage(), e);
              }
      
          }
      
      }
      
    • AngularJs Service : download.service.js

      (function() {
          'use strict';
      
          var downloadModule = angular.module('components.donwload', []);
      
          downloadModule.factory('downloadService', ['$q', '$timeout', '$window',
              function($q, $timeout, $window) {
                  return {
                      download: function(name) {
      
                          var defer = $q.defer();
      
                          $timeout(function() {
                                  $window.location = 'download?name=' + name;
      
                              }, 1000)
                              .then(function() {
                                  defer.resolve('success');
                              }, function() {
                                  defer.reject('error');
                              });
                          return defer.promise;
                      }
                  };
              }
          ]);
      })();
      
    • AngularJs config : app.js

      (function() {
          'use strict';
      
          var myApp = angular.module('myApp', ['components.donwload']);
         /* myApp.config([function () {
      
          }]);
          myApp.run([function () {
      
          }]);*/
      
      
      })();
      
    • AngularJs controller : download.controller.js

      (function() {
          'use strict';
      
          angular.module('myApp')
              .controller('DownloadSampleCtrl', ['downloadService', function(downloadService) {
                  this.download = function(fileName) {
                      downloadService.download(fileName)
                          .then(function(success) {
                              console.log('success : ' + success);
                          }, function(error) {
                              console.log('error : ' + error);
                          });
                  };
              }]);
      })();
      
    • index.html

      
      
      
      
          My App
          
          
          
      
      
      
          

提交回复
热议问题