欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java上传下载功能的实现,java上传下载实现,上传下载是很简单的功能,

来源: javaer 分享于  点击 32398 次 点评:284

Java上传下载功能的实现,java上传下载实现,上传下载是很简单的功能,


上传下载是很简单的功能,但是每次用的时候还是要查,这里整理一下

前台:

  <form action="xxoo.do" enctype="multipart/form-data" method="post">    <input type="file" name="file" />     <button type="submit" class="btn btn-primary"> 提交  </form>

主要注意:

 enctype="multipart/form-data" method="post"

后台:

各种框架都有自己的上传下载功能,实现也是大同小异,说到底上传就是复制文件,需要一个输出流。通过firebug以看到上传时,会有两个参数传到后台,一个是文件流,这个变量名与input 中的name一致;还有一个就是文件名,默认是filename。

如果使用struts2。文件名是文件流的变量名+FileName。如上是fileFileName。

后台直接:FileUtils.copyFile(shopDatas, tempFile);这里没有使用框架的上传功能

下载的话,实际上就是传一个inputstream,往外读数据。懒得使用框架的功能,可以直接使用response响应

public void downLoad(String newFileName){    InputStream is = null;    OutputStream os = null;    HttpServletResponse response = ServletActionContext.getResponse();    try{        String contentType="application/octet-stream";          response.setContentType(contentType);          response.setHeader("Content-disposition","attachment;filename=\""+newFileName+"\"");        is=new BufferedInputStream(new FileInputStream(newFileName));                ByteArrayOutputStream baos=new ByteArrayOutputStream();          os=new BufferedOutputStream(response.getOutputStream());              byte[] buffer=new byte[4*1024];           int read=0;            while((read=is.read(buffer))!=-1){              baos.write(buffer,0,read);          }          os.write(baos.toByteArray());          }catch(Exception e){            e.printStackTrace();        }finally{            closeStream(os, is);        }    }
相关栏目:

用户点评