使用Java servlet从Tomcat服务器下载mp3文件

时间:2013-03-31 05:31:24

标签: java tomcat servlets downloadfile

我正在建立一个管理音乐的网站,但我不知道如何从我的servlet下载mp3。

这是我的代码:

  filename=new File(imagepath).getName();
  FileOutputStream fil=new FileOutputStream(pathfolder+"/"+filename);

  URL url=new URL("http://192.168.1.4:8080/Demo/upload/"+filename);

  HttpURLConnection urlconnection=null;
  urlconnection=(HttpURLConnection)url.openConnection();

  urlconnection.setRequestMethod("GET");
  urlconnection.setDoOutput(true);
  urlconnection.connect();


  int total_size=urlconnection.getContentLength();
  Log.i("totall sizeeeeeee",""+total_size);
  InputStream inpstream = urlconnection.getInputStream();
  byte[] buffer=new byte[total_size];
  int buffleng=0,download_size=0;
  while((buffleng=inpstream.read(buffer))>0)
  {

  fil.write(buffer,0,buffleng);

  }

  }
  catch(Exception ex){

      ex.printStackTrace();

  }

1 个答案:

答案 0 :(得分:1)

ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
  stream = response.getOutputStream();
  File mp3 = new File("/myCollectionOfSongs" + "/" + fileName);

  //set response headers
  response.setContentType("audio/mpeg"); 

  response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

  response.setContentLength((int) mp3.length());

  FileInputStream input = new FileInputStream(mp3);
  buf = new BufferedInputStream(input);
  int readBytes = 0;
  //read from the file; write to the ServletOutputStream
  while ((readBytes = buf.read()) != -1)
    stream.write(readBytes);
} catch (IOException ioe) {
  throw new ServletException(ioe.getMessage());
} finally {
  if (stream != null)
    stream.close();
  if (buf != null)
    buf.close();
}