【问题标题】:Download mp3 file from Tomcat server with Java servlet [closed]使用 Java servlet 从 Tomcat 服务器下载 mp3 文件 [关闭]
【发布时间】:2013-03-21 12:53:55
【问题描述】:

我正在创建一个网站来管理音乐,但我不知道如何从我的 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();

  }

【问题讨论】:

  • 嗯...像下载音乐的代理?

标签: java tomcat servlets downloadfile


【解决方案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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 2016-05-24
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    相关资源
    最近更新 更多