2017-06-30 36 views
0

我有要求用戶可以上傳文件,以及其他用戶看到他可以下載文件。新的要求表明,現在用戶可以上傳多個附件,任何看到它的用戶都可以下載多個附件。例外:在下載多個附件時關閉流

因此,我拿了一個附件添加的列表,並將其指向下載控制器,我更改了早期的行並保留了一個for循環,但是在下載過程中只有第一個附件被下載,隨後它會使異常流被關閉。是控制器的代碼。請讓我知道我該怎麼過來呢?

@ApiOperation(value = "Download content") 
@RequestMapping(value = "/api/content/{id}/download/", method = RequestMethod.GET) 
public ResponseEntity<String> downloadContent(HttpServletResponse response, @PathVariable("id") final Long id) 
     throws IOException, APIException { 
    Content content = null; 
    try { 
     content = this.contentService.get(this.contentUtils.getContentObject(id)); 
    } catch (ServiceException e) { 
     throw new APIException("Access denied"); 
    } 
    if (null == content) { 
     throw new APIException("Invalid content id"); 
    } 
    List<Document> documentList = this.contentService.getDocumentByContent(content); 
    if (documentList != null && !documentList.isEmpty()) { 
     //Document document = documentList.get(0); //If multiple files supported?, then need to be handled here 
     for (Document document : documentList) { 
      File file = new File(document.getLocalFilePath()); 
      if (file.exists()) { 
       response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\""); 
       try (InputStream inputStream = new FileInputStream(file); ServletOutputStream sos = response.getOutputStream();) { 
        IOUtils.copy(inputStream, sos); 
       } catch (final IOException e) { 
        LOGGER.error("File not found during content download" + id, e); 
        throw new APIException("Error during content download:" + id); 
       } 
      } else { 
       try { 
        s3FileUtil.download(document.getS3Url(), document.getLocalFilePath()); 
       } catch (S3UtilException e) { 
        throw new APIException("Document not found"); 
       } 
      } 
     } 
    } else { 
     //404 
     return new ResponseEntity<String>(HttpStatus.NOT_FOUND); 
    } 
    return new ResponseEntity<String>(HttpStatus.OK); 
} 

回答

0

實際上,您無法一次下載所有文件。因爲一旦你打開一個流並將文件內容寫入流,你必須關閉這個流。

當您在for循環中添加文件時,您必須附加文件內容而不是文件,這不是預期的行爲。

當你想同時下載多個文件,你必須拉鍊 的文件和下載。

檢查此鏈接:download multiple files