日期:2014-05-17  浏览次数:20725 次

java 从web服务器下再文件,采用什么方法?
请各位大侠提供方法,或代码谢谢!
我是需要从web界面提供下载按钮,点击下载后,下载web服务器上指定的文件保存到本地计算机用户选择的文件家中。
我现在采用的window.open方式,但是有问题,有的计算机可以正常弹出保存文件对话框,有的计算机确直接播放,有的则没反应,服务器上的文件是wav音频文件。
各位指点下,帮帮忙!

------解决方案--------------------
response.setContentType("audio/wav");

ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("...xx.wav");

int read = 0;
byte[] bytes = new byte[1024];

OutputStream os = response.getOutputStream();
while ((read = is.read(bytes)) != -1) {
  os.write(bytes, 0, read);
}
os.flush();
os.close();
------解决方案--------------------
js中
超链接到这个方法就行(我传的是id)
action中
public void downloadByObjId(HttpServletRequest request, HttpServletResponse response, String id)
/*     */   {
/*     */     try
/*     */     {
/* 101 */       Attachment attachment = (Attachment)this.attachmentManager.get(id);
/*     */ 
/* 103 */       response.setContentType("text/plain");
/* 104 */       response.setHeader("Content-Disposition", "attachment; filename=" + new String(attachment.getFileName().getBytes(), "ISO-8859-1"));
/*     */ 
/* 106 */       File file = new File(attachment.getFilePath());
/* 107 */       FileInputStream fis = new FileInputStream(attachment.getFilePath());
/* 108 */       BufferedInputStream buff = new BufferedInputStream(fis);
/* 109 */       Long fileLong = Long.valueOf(file.length());
/* 110 */       response.setContentLength(Integer.valueOf(fileLong.toString()).intValue());
/* 111 */       byte[] b = new byte[1024];
/*     */ 
/* 113 */       OutputStream out = response.getOutputStream();
/*     */       int j;
/* 115 */       while ((j = buff.read(b)) > 0)
/*     */       {
/*     */         int j;
/* 117 */         out.write(b, 0, j);
/*     */       }
/* 119 */       buff.close();
/* 120 */       fis.close();
/* 121 */       out.flush();
/* 122 */       out.close();
/*     */     } catch (