📄 downloadservlet.java
字号:
package music.web;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import music.web.MusicViewBD;
/**
* use like this:
* http://ip-address/url-mapping?id=###
*/
public class DownloadServlet extends HttpServlet {
private static String prefix = null;
public void init(ServletConfig config) throws ServletException {
// 获得文件起始路径:
prefix = config.getInitParameter("prefix");
if(prefix==null) prefix = "";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
int id = 0;
try {
id = Integer.parseInt(request.getParameter("id"));
}
catch(Exception e) {
throw new ServletException("Parameter expected.");
}
String url = null;
try {
url = new MusicViewBD().download(id);
System.out.println("<log> downloading " + prefix + url);
}
catch(Exception e) {
throw new ServletException(e);
}
InputStream dis = null;
OutputStream dos = null;
File file = new File(prefix+url);
int filesize = (int)file.length();
response.reset();
response.setContentType("application/octet-stream; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment; filename="
+ java.net.URLEncoder.encode(file.getName(), "UTF-8"));
response.setContentLength(filesize);
try {
dis = new BufferedInputStream(new FileInputStream(file));
dos = response.getOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while((n=dis.read(buffer))!=(-1)) {
dos.write(buffer, 0, n);
}
dis.close();
dis = null;
dos.close();
dos = null;
response.flushBuffer();
}
catch(IOException ioe) {
System.out.println("-- download error: " + ioe.getMessage());
}
finally {
if(dis!=null) dis.close();
if(dos!=null) dos.close();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
{
throw new ServletException("POST is not support.");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -