首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

java 从web服务器停再文件,采用什么方法

2013-04-05 
java 从web服务器下再文件,采用什么方法?请各位大侠提供方法,或代码谢谢!我是需要从web界面提供下载按钮,

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 (FileNotFoundException e1) {
/* 124 */       this.log.error("文件没有找到: " + e1.getMessage());


/*     */     } catch (SocketException e2) {
/* 126 */       this.log.error("用户取消文件下载: " + e2);
/*     */     } catch (Exception e) {
/*     */       try {
/* 129 */         response.getWriter().write("error");
/*     */       } catch (IOException e1) {
/* 131 */         e1.printStackTrace();
/*     */       }
/* 133 */       this.log.error("下载文件时错误: " + e);
/*     */     }
/*     */   }


Attachment   是写的下载类
attachment.getFilePath()  是下载路径
attachment.getFileName()  是下载名称

热点排行