2016-02-12 78 views
4

我跟隨spark github頁面的討論以及堆棧溢出瞭解如何使用spark和apache文件上傳上傳文件。下載圖片在火花java

現在我想要用戶有一個選項來單擊下載圖像。

例如,我上傳的文件存儲在服務器上的/tmp/imageName.jpg中。

在客戶端我想給用戶一個選項,當用戶點擊超鏈接時下載文件。

<a href="/image/path">click here</a> 

當用戶點擊超鏈接時,我會用文件路徑調用函數,但無法理解如何發送圖像作爲響應。

我知道HTML5有download attribute,但這需要將文件保存在服務器上的公用文件夾中,這是不可能的。

我在以前的類似問題加入去試圖複製了我的方案沒有成功

How can I send a PNG of a QR-code in a HTTP response body (with Spark)?

How download file using java spark?

編輯: 我沒有按照答案強制下載所提供的鏈接圖像,但使用response.raw()我無法得到迴應

response.type("application/force-download"); 
     response.header("Content-Transfer-Encoding", "binary"); 
     response.header("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName); 
     try { 
     HttpServletResponse raw = response.raw(); 
     PrintWriter out = raw.getWriter(); 
     File f= new File("/tmp/Tulips.jpg"); 

     InputStream in = new FileInputStream(f); 
     BufferedInputStream bin = new BufferedInputStream(in); 
     DataInputStream din = new DataInputStream(bin); 

     while(din.available() > 0){ 
      out.print(din.read()); 
      out.print("\n"); 
     } 

     } 
     catch (Exception e1) { 
      e1.printStackTrace(); 
     } 
     response.status(200); 
     return response.raw(); 

編輯2:

我不確定使用response.body()與response.raw()。someFunction()之間有什麼區別。無論是哪種情況,我似乎都可以將數據發回給您。即使我寫了一個簡單的response.body(「hello」),它並不反映在我的回覆中。

與圖像相比,文件的讀取方式有什麼區別嗎?使用ImageIO類進行抽樣?

+0

的可能的複製[?如何強制瀏覽器下載文件] (http://stackoverflow.com/questions/6520231/how-to-force-browser-to-download-file) –

+0

response.raw(); // Jetty提交的原始響應 –

+0

response.body(「Hello」); //將內容設置爲Hello –

回答

3

下面是爲我工作的解決方案:

Service.java

get(API_CONTEXT + "/result/download", (request, response) -> { 

     String key = request.queryParams("filepath"); 
     Path path = Paths.get("/tmp/"+key); 
     byte[] data = null; 
     try { 
      data = Files.readAllBytes(path); 
     } catch (Exception e1) { 

      e1.printStackTrace(); 
     } 

     HttpServletResponse raw = response.raw(); 
     response.header("Content-Disposition", "attachment; filename=image.jpg"); 
     response.type("application/force-download"); 
     try { 
      raw.getOutputStream().write(data); 
      raw.getOutputStream().flush(); 
      raw.getOutputStream().close(); 
     } catch (Exception e) { 

      e.printStackTrace(); 
     } 
     return raw; 


    }); 

角碼

$scope.downloadImage= function(filepath) { 
     console.log(filepath); 
     window.open('/api/v1/result/download?filepath='+filepath,'_self',''); 
    }