2017-01-31 78 views
0

我已經四處尋找解決方案,但無法找到任何解決方案。從春季URL打開文件標記

我在我本地驅動器中存儲一個文件,並在我的mongoDB中存儲該文件的路徑, 在檢索我想爲URL提供URL的路徑之後從DB獲取路徑。當我點擊該URL時,該路徑應該打開該相關文件。
我的代碼如下

數據以dB爲:

"filePath" : "C:/myfiles/Resume_Vipul.docx" 

在前端訪問它:

<c:forEach var="ser" items="${services}" varStatus="status"> 
<td class="text-center"><a href='<spring:url value="${ser.filePath}" />'>file</a></td> 
</c:forEach> 

當我點擊的網址它給了我錯誤爲:

Not allowed to load local resource: file:///C:/myfiles/Resume_Vipul.docx 

執行此操作的正確方法是什麼? 任何幫助,將不勝感激。

+0

在你的'web.xml'中爲你的目錄添加一個servlet映射,並使用映射別名替換你的'$ {ser.filePath}'' –

回答

0

你應該發送到控制器的請求採取的文件名作爲參數,併發送回的字節響應,這樣的事情,

ServletContext cntx= req.getServletContext(); 
    // Get the absolute path of the image 
    String filename = cntx.getRealPath("Images/button.png"); 
    // retrieve mimeType dynamically 
    String mime = cntx.getMimeType(filename); 
    if (mime == null) { 
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
    return; 
    } 

    resp.setContentType(mime); 
    File file = new File(filename); 
    resp.setContentLength((int)file.length()); 

    FileInputStream in = new FileInputStream(file); 
    OutputStream out = resp.getOutputStream(); 

    // Copy the contents of the file to the output stream 
    byte[] buf = new byte[1024]; 
    int count = 0; 
    while ((count = in.read(buf)) >= 0) { 
    out.write(buf, 0, count); 
    } 
out.close(); 
in.close(); 

從客戶端訪問本地資源,我認爲不是好主意。考慮向服務器提出一個單獨的請求。在你的情況下,你可以將資源路徑作爲String參數發送到服務器。

+0

我會試着實現這個 –