下载文件:
//通过路径得到一个输入流 String path = "获取需要下载的文件路径"; //path.lastIndexOf(".")+1可以获取文件后缀名字 如:doc等 //this.getServletContext().getRealPath("");可以访问当前服务器地址 String fileName="保存文件的名称" ; //设置保存文件的乱码问题 String encodedfileName = null; String agent = request.getHeader("USER-AGENT"); if(null != agent && -1 != agent.indexOf("MSIE")){//IE encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8"); }else if(null != agent && -1 != agent.indexOf("Mozilla")){ encodedfileName = new String (fileName.getBytes("UTF-8"),"iso-8859-1"); }else{ encodedfileName = java.net.URLEncoder.encode(fileName,"UTF-8"); } //设置响应格式 response.setHeader("content-disposition", "attachment;filename=encodedfileName); //输入流,获得文件的字节流 InputStream is=new FileInputStream(path);//path是下载文件的路径 byte[] bytes=new byte[is.available()]; is.read(bytes); //将字节流写入response中 response.getOutputStream().write(bytes); is.close(); response.flushBuffer(); response.getOutputStream().flush();
上传文件:
//设置上传的路径 String savePath=this.getServletConfig().getServletContext().getRealPath(""); File file=new File(savePath); //判断是否存在 不存在就创建 if(!file.exists()){ file.mkdirs(); } DiskFileItemFactory fac=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8"); List<FileItem> filelist=null; try { filelist=upload.parseRequest(request); } catch (FileUploadException e) { // TODO Auto-generated catch block return; } Iterator<FileItem> it=filelist.iterator(); String name=""; String extName=""; while(it.hasNext()){ FileItem item=it.next(); if(!item.isFormField()){ name=item.getName(); long size=item.getSize(); String type=item.getContentType(); //判断是否为空 if(name==null||name.trim().equals("")){ continue; } if(name.lastIndexOf(".")>=0){ extName=name.substring(name.lastIndexOf(".")); } File files=null; name=id; files=new File(savePath+name+extName); try { item.write(files); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
response.getWriter().print("上传成功"); }
需要两个包:
commons-io-1.4.jar
commons-fileupload-1.2.1.jar
下载地址:https://github.com/weibanggang/iofilego
希望能够帮助大家,有问题请留言,感谢!