2017-10-03 10 views
-1

サーバーからのダウンロード要求を処理するJavaコントローラを作成しました。私のファイルはサーバーに存在しますが、毎回0 KBのファイルがダウンロードされています。ファイルはダウンロードされていますが、サイズは常に0 KBです。私を助けてください。Javaファイルのダウンロード - ダウンロードしたファイルサイズは常に0です。Kb

@RequestMapping(value="/downloadFile/{docId}") 
    public void getDownloadFile(@PathVariable(value = "docId") Integer docId, HttpServletResponse response) throws Exception { 
     String userName = getUserName(); 
     try { 
      DocVault documentsVault = documentsVaultRepository.findDocumentAttachment(docId); 
      String fileName = documentsVault.getDocumentName(); 
      int customerId = documentsVault.getCustomerId(); 

      Map<Integer, String> customerInfo = cspUtils.getCustomersInfo(userName); 
      Set<Integer> customerIds = customerInfo.keySet(); 
      for (int custId : customerIds) { 
       if (custId == customerId) { 
        String path = env.getProperty("doc.rootfolder") + File.separator + documentsVault.getFileName(); 
        service.downloadFile(fileName, path, response); 
       } else { 
        logger.info("Customer not linked to user"); 
       } 
      } 
     } catch (Exception e) { 
      logger.error(e.getMessage(), e); 
     } 
    } 

実装 - - 私は例外を取得していないです

public void downloadFile(String fileName, String path, HttpServletResponse response) { 

     try { 
      File downloadFile = new File(path); 
      FileInputStream inputStream = new FileInputStream(downloadFile); 

      response.setContentLength((int) downloadFile.length()); 
      response.setHeader("Content-Disposition", "attachment;filename=" + fileName); 

      // get output stream of the response 
      OutputStream outStream = response.getOutputStream(); 

      byte[] buffer = new byte[BUFFER_SIZE]; 
      int bytesRead = -1; 

      // write bytes read from the input stream into the output stream 
      while ((bytesRead = inputStream.read(buffer)) != -1) { 
       outStream.write(buffer, 0, bytesRead); 
      } 
      inputStream.close(); 
      outStream.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

ここに私のコードです。助けてください。 ありがとうございます。

答えて

0

ありがとうございました。私が気づいたのは、私のContent Dispositionヘッダーに問題があったということでした。私は拡張子のないファイル名だけを渡していました。私は完全なファイル名を渡したとき、それは完全に働いた。ファイルのサイズと拡張子は適切でした。

0
response.setContentLength((int) downloadFile.length()); 

これを削除します。コンテナによって自動的に設定されます。

int bytesRead = -1; 

この変数を初期化する必要はありません。次の行に割り当てられます。

+0

ありがとうございます。今サイズは大丈夫です。しかし、ファイルタイプは.txt、.pdf、.docなどの代わりに 'ファイル'としてダウンロードされています。お手伝いできますか?以前はこの問題もありました。 –

+0

- おそらく、 'Content-Disposition'ヘッダが返される(dev consoleかfiddlerを通して)かどうかを確認してください。私はあなたが正しく設定されていることを確認しますが、ブラウザに返された実際の値が何であるかを確認してください。 – gusto2

+0

@HarshitGupta 'save as'ビジネスは、あなたが 'Content-disposition'として送信しているものに完全に依存します。 – EJP

関連する問題