2014-08-27 34 views
2

我正在使用我的服務器來分發一些文件(在zip中),但是,我希望用戶在能夠下載文件之前輸入CAPTCHA。HttpExchange發送文件

這提出了一個新的問題,因爲代碼:

private void sendFileResponse(final String filename, byte[] response, HttpExchange httpExchange) { 
     //<editor-fold defaultstate="collapsed" desc="code"> 
     if (response != null && response.length > 0 && httpExchange != null) { 
      try { 
       httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/zip"); 

       OutputStream outputStream = httpExchange.getResponseBody(); 
       httpExchange.sendResponseHeaders(200, response.length); 
       outputStream.write(response); 
       outputStream.flush(); 
       outputStream.close(); 
       httpExchange.getRequestBody().close(); 
      } catch (Exception e) { 
       System.out.println(Misc.getStackTrace(e)); 
      } 
     } 
     //</editor-fold> 
    } 

...將導致文件被命名爲下載請求的網頁的URL。例如,如果用戶輸入正確的驗證碼並在/download.html下載文件,則他們收到的文件將爲download.html,而不是我的文件名。

如何讓服務器發送文件作爲文件的名稱,並使網頁同時刷新?

謝謝。

+0

我敢肯定,這是一個重複,但似乎無法找到原來現在... – 2014-08-27 19:21:05

回答

4

使用內容處置 HTTP標頭字段:

內容處置:附件;文件名= yourfilename

httpExchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=" + filename); 
+1

@使用httpExchange.getResponseHeaders()user3635998嘗試。加上(「內容處置」 ,「attachment; filename =」+ filename +「;」); – J4v4 2014-08-27 19:39:52

+0

我剛剛得到它與相同的事情,並編輯了你的答覆。感謝您的幫助。 – user3635998 2014-08-27 19:41:22

+0

我將代碼添加到答案中。您應該始終使用getRequestHeaders()或getResponseHeaders()。我真的不知道setAttribute()有什麼好處,但其他兩個聽起來很直接。 – J4v4 2014-08-27 19:45:04