我想在用户点击“下载音乐”链接时向用户显示如下所示的弹出窗口?
如果我使用以下代码,那么点击链接后会打开浏览器嵌入式音乐播放器,如Apple RealTIme ..
<a href="../mp3/horse.mp3" target="_blank">Click to download</a>
如何阻止浏览器运行音乐(不禁用/删除此插件)。
我希望我的浏览器应该下载音乐而不应该播放它!
答案 0 :(得分:1)
首先,从锚点中删除onclick
属性。您无需为此涉及JavaScript。
其次,让您的服务器在请求mp3时返回content-disposition: attachment
HTTP响应标头。如何执行此操作取决于您的服务器。例如,在Apache中,如果不涉及服务器端编程语言,则可以使用a Header
directive。或者,请参阅an example in Java(尽管您应为mp3设置正确的content-type
。)
答案 1 :(得分: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
答案 2 :(得分:0)
您可以在服务器的.htaccess文件中添加以下代码行,以强制从服务器下载特定的文件类型。然后一个正常的链接应该工作。
<FilesMatch "\.(?i:mp3)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
答案 3 :(得分: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 :)
答案 4 :(得分:-1)
单击链接调用强制将文件写入浏览器的servlet。 然后由浏览器下载。 读取文件,然后将其写入响应