2013-01-20 49 views
0

當他點擊「下載音樂」鏈接時,我想向用戶顯示如下所示的彈出窗口?如何在網頁上添加下載音樂鏈接?

enter image description here

如果我使用點擊一個鏈接後,然後下面的代碼打開了瀏覽器內嵌音樂播放,如蘋果的實時..

<a href="../mp3/horse.mp3" target="_blank">Click to download</a> 

如何防止瀏覽器運行音樂(沒有禁用/刪除這個插件)。

我想我的瀏覽器應該下載音樂,不應該玩它!

回答

1

首先,從錨點中刪除onclick屬性。你不需要爲此涉及JavaScript。

其次,請求MP3時,讓您的服務器返回一個content-disposition: attachment HTTP響應標頭。你如何做到這一點取決於你的服務器。例如,在Apache中,如果不涉及服務器端編程語言,則可以使用a Header directive。或者,請參閱an example in Java(儘管您應該爲mp3設置正確的content-type)。

+0

感謝哥們!有效! :) –

-1

點擊鏈接調用強制將文件寫入瀏覽器的servlet。它會被瀏覽器下載。 讀取文件,然後將其寫入響應

+0

有力嗎?你什麼意思? – Quentin

+0

我們只需要使用流讀取文件,然後將其寫入瀏覽器。當我們寫入瀏覽器時,它會強制瀏覽器下載它。您需要將內容處置和內容類型放在標題部分。 謝謝 – Learner

+0

不,這會得到與直接從網絡服務器訪問相同的結果。 – Quentin

0

您可以在服務器的.htaccess文件中添加以下幾行代碼,以強制從服務器下載特定文件類型。然後一個正常的鏈接應該工作。

<FilesMatch "\.(?i:mp3)$"> 
    ForceType application/octet-stream 
    Header set Content-Disposition attachment 
</FilesMatch> 
0
Explaining here how I did it: 

1. Add following snippet in web.xml: 



<pre><code> 
<servlet> 
     <servlet-name>MyDownloadServlet</servlet-name> 
     <servlet-class>com.lokur.MyDownloadServlet</servlet-class>  
    </servlet> 
    <servlet-mapping> 
     <servlet-name>MyDownloadServlet</servlet-name> 
     <url-pattern>*.download</url-pattern> 
    </servlet-mapping> 

</pre></code> 

2. Add following in your servlet: 



public class MyDownloadServlet extends HttpServlet { 

    private static final long serialVersionUID = 1L; 

    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse response) 
      throws ServletException, IOException { 


     //Set the headers. 
     response.setContentType("application/x-download"); 
     response.setHeader("Content-Disposition", "attachment; filename=downloaded_horse.mp3"); 

    //TODO: pull the file path from the request parameters 
     InputStream fileIn = getServletContext().getResourceAsStream("mp3/horse.mp3"); 
     ServletOutputStream outstream = response.getOutputStream(); 

     byte[] outputByte = new byte[40096]; 

     while(fileIn.read(outputByte, 0, 40096) != -1) 
     { 
      outstream.write(outputByte, 0, 40096); 
     } 
     fileIn.close(); 
     outstream.flush(); 
     outstream.close(); 


    } 


} 


3. Finally this is the requested jsp: 


<pre> <code> 
     <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
     pageEncoding="ISO-8859-1" 

    %> 
    <body> 
    <form action="getMusicFile.download" method="post"> 
     Wanna download? <input type="submit" value="Download music"> 
     </form> 
    </body> 



That's all to it! 

Cheers, 
Akshay :) 
1

上nginx的,您可以在nginx.conf添加此

location ~* (.*\.mp3) { 
    types { application/octet-stream .mp3; } 
    default_type application/octet-stream; 
} 

,並在Apache中添加這對你的httpd.conf或的.htaccess

<FilesMatch "\.(?i:mp3)$"> 
    ForceType application/octet-stream 
    Header set Content-Disposition attachment 
</FilesMatch> 

我在http://mp3boo.cc配置上使用此功能,並很好地強制下載mp3文件。 hth