2016-03-21 35 views
2

我有一個angularjs應用程序部署在服務器中,而應用程序部署在另一臺服務器上。使用angularjs和彈簧啓動上傳文件

在我angularjs應用我有上傳文件,並通過休息控制器發送形式,該控制器然後保存在春季啓動應用程序部署在服務器中的文件夾內的文件。

這是我的休息控制器:

@CrossOrigin(origins="*") 
@RestController 
public class Upload { 

    @RequestMapping(value="/imageUpload", method = RequestMethod.POST) 
    public void UploadFile(MultipartHttpServletRequest request) throws IOException { 

     Iterator<String> itr=request.getFileNames(); 
     MultipartFile file=request.getFile(itr.next()); 
     String fileName=file.getOriginalFilename(); 
     File dir = new File("C:\\file"); 
     if (dir.isDirectory()) 
     { 
      File serverFile = new File(dir,fileName); 
      BufferedOutputStream stream = new BufferedOutputStream(
        new FileOutputStream(serverFile)); 
      stream.write(file.getBytes()); 
      stream.close(); 
     }else { 
      System.out.println("not"); 
     } 

    } 
} 

,這我angularjs控制器發送該文件:

$scope.validerOffre= function(){ 
    var file = $scope.fileUpload; 
    var uploadUrl = "/imageUpload"; 
    fileUploadService.uploadFileToUrl(file, uploadUrl); 
    }; 

該控制器然後調用fileUploadService:

capValueRecruitApp.service('fileUploadService', function ($http) { 
    this.uploadFileToUrl = function(file, uploadUrl){ 
    var fd = new FormData(); 
    fd.append('file', file); 
    $http.post('http://localhost:8080' + uploadUrl, fd, { 
     transformRequest: angular.identity, 
     headers: {'Content-Type': undefined} 
     }) 
     .success(function(){ 
     }) 
     .error(function(){ 
     }); 
    } 
}); 

,並在我的angularjs應用程序我想顯示我上傳的文件,但我不能這樣做,因爲這些文件是在另一臺服務器的春季啓動應用程序服務器上傳的。

所以我的問題是我怎麼能救我上傳的文件夾中的應用angularjs服務器,而不是在春天啓動的應用程序部署在服務器上的文件。

回答

1

你基本上有兩種解決方法:

1:創建一個新的@RequestMapping,是以文件名(甚至更好您的FileUpload控制器返回一個id),並返回該文件。 是這樣的:

@RequestMapping(value="/imageDownload", method = RequestMethod.POST) 
public void downloadFile(@RequestParam(value = "fileName", required = true) String fileName,HttpServletResponse response) throws IOException { 

    File dir = new File("C:\\file"); 
    File fileToDownload = new File(dir,fileName); 
    if (dir.isDirectory() && fileToDownload.exists()){ 
     //read fileToDownload and send stream to to response.getOutputStream(); 

    }else { 
     System.out.println("no such file "+ fileToDownload.toString()); 
     response.sendError(404); 
     return; 
    } 

} 

然後調用http://localhost:8080/imageDownload?filename=yourUploadedFile.jpg

2:當您保存在上傳文件時,某個地方將它保存在你的網絡服務器直接訪問。

如果我們的angularjs文件由您的spring應用程序提供,您可以在application.properties文件中的spring.resources.staticLocations中添加一個新文件夾。 (看到這一點:http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content