2016-09-23 2 views
0

내 AngularJS 웹 사이트에서 .pdf 문서를로드하고 새 브라우저 탭에 표시하고 싶습니다. 다음 코드는 작동하지만 일부 문제는 나를 귀찮게합니다.AngularJS 새 탭에서 PDF 파일을 열고 파일 이름/URL을 변경하십시오.

createdObjectURL은 문서 및 브라우저 탭의 제목으로 설정됩니다. 즉, 내 문서는 항상 01d9bdca-9af2-43f0-a83f-f36fd82fd72과 같이 제목이 붙어 있습니다. 실제로는별로 좋지 않습니다. 그리고 보이는 URL도 좋지 않습니다. blob:http://localhost:8080/01d9bdca-9af2-43f0-a83f-f36fd82fd72f 대신 service.js에서 호출하는 URL을 사용하는 것이 좋습니다.

은 내가 HttpHeaders에서 파일 이름을 처리하려하지만 전혀 효과가 없습니다 :(

또 다른 이상한 일이 : 나는 {responseType: "arraybuffer"}를 지정하지 않은 경우, PDF-제목이 올바르게 표시 그러나이된다. 어떤 내용이 문서가 비어 없습니다.

파일 이름을 변경하는 및/또는 URL이 평가 될 것입니다 방법에 대한 도움이됩니다. 감사합니다.

JS 컨트롤러

DocumentService.getDocument().then(function(response) { 
    $window.open(response, '_blank'); 
}); 

JS 서비스

return { 
    getDocument : function() { 
    return $http.get("document", {responseType: "arraybuffer"}) 
     .then(function(response) { 
     var file = new Blob([response.data], {type: "application/pdf"}); 
     var fileURL = URL.createObjectURL(file); 
     return fileURL; 
     } 
    } 
} 

스프링 MVC REST 서비스

@RequestMapping(value = "/document", method = RequestMethod.GET) 
public ResponseEntity<byte[]> getDocument(){ 
    try { 
    File file = new File("C:\\pathToFile.pdf"); 
    byte[] fileContent = new byte[(int) file.lenth()]; 

    HttpHeaders heraders = new HttpHeaders(); 
    headers.setContentType(MediaType.parseMediaType("application/pdf")); 
    String filename = "NameOfFile.pdf"; 
    headers.setContentDispositionFormData(filename, filename); //doesn't change anything 

    fileContent = File.readAllBytes(file.toPath()); 

    ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(fileContent, headers, HttpStatus.OK); 

    return response; 
    } catch (FileNotFoundException e) { 
    System.err.println("File not found " + e); 
    } catch (IOException e) { 
    System.err.pringln("Error while reading file " + e); 
    } 
} 

짧은 버전 : PDF 파일은 그것을 바이트 배열로로드하여 표시 AngularJS $ window 지시어가있는 새로운 브라우저 탭 : 파일 이름과 URL을 변경할 가능성이 있습니까?

+1

바이트 배열을 반환하는 리소스에 대한 URL로 새 탭을 열 수 없습니까? '$ window.open ('localhost : xxx/api/document', '_blank'); ' – Amygdaloideum

+0

@DanielBornstrand, 고맙습니다. 창 제목은 이제'document'이지만 문서가 다운로드되면 문서 제목이 내가 지정한 것입니다. 이것은 100 % 완벽하지는 않지만 이전보다 더 좋고 코드도 적습니다 :) – Freddy

+0

나는 대답으로 게시 할 것입니다! :) – Amygdaloideum

답변

3

바이트 배열을 반환하는 리소스에 대한 URL로 새 탭을 엽니 다! 다음과 같이하십시오 :

관련 문제