java文件上传下载 - 源码分享

  时间:2018-11-07
本文章向大家介绍java文件上传下载 - 源码分享,需要的朋友可以参考一下

文件上传

  @RequestMapping(value="/uploadFile",method=RequestMethod.POST)
  public ResultObject uploadFiles(@RequestParam("file")MultipartFile file,HttpServletRequest request){
       ResultObject rs = null;//返回上传完成信息
       String uploadDir = "files";//上传目录,文件保存在webapp下的files文件中
      if(!file.isEmpty()) {
          //可以对user做一些操作如存入数据库
          //以下的代码是将文件file重新命名并存入Tomcat的webapp目录下项目的下级目录
          String fileRealName = file.getOriginalFilename();                   //获得原始文件名;
          /*int pointIndex = fileRealName.indexOf(".");                        //点号的位置
          String fileSuffix = fileRealName.substring(pointIndex);             //截取文件后缀
          UUID FileId = UUID.randomUUID();                        //生成文件的前缀包含连字符
          String savedFileName = FileId.toString().replace("-", "").concat(fileSuffix);       //文件存取名
          */
         
          String savedDir = request.getSession().getServletContext().getRealPath(uploadDir); //获取服务器指定文件存取路径
          File savedFile = new File(savedDir, fileRealName);
          boolean isCreateSuccess;
          try {
              isCreateSuccess = savedFile.createNewFile();
              if (isCreateSuccess) {

                  file.transferTo(savedFile);  //转存文件
                  rs = ResultObject.getSuccessResult("上传文件成功");
                  Long size = file.getSize();//获取文件大小


                  rs.setData(uploadDir+fileRealName);
              }else{
                  rs = ResultObject.getFailResult("请修改文件名,重新上传");
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }else{
          rs = ResultObject.getFailResult("文件不能为空");
      }
      return rs;
  }

文件下载

@RequestMapping(value = "/filterPermission/appDownLoad", method = RequestMethod.GET)
    public void appDownLoad(HttpServletRequest request, HttpServletResponse response) {
        //url是上面文件上传的url
        download(url,request,response);
    }
public String download(String filePath, HttpServletRequest request, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //获取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            //response.setContentType("application/force-download");
            //处理下载弹出框名字的编码问题
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
            //获取文件的下载路径
            String path = request.getSession().getServletContext().getRealPath(filePath);
            //利用输入输出流对文件进行下载
            InputStream inputStream = new FileInputStream(new File(path));
            //设置文件大小
            response.setHeader("Content-Length", String.valueOf(inputStream.available()));

            bis = new BufferedInputStream(inputStream);//构造读取流
            bos = new BufferedOutputStream(response.getOutputStream());//构造输出流
            byte[] buff = new byte[1024];
            int bytesRead;
            //每次读取缓存大小的流,写到输出流
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            response.flushBuffer();//将所有的读取的流返回给客户端

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try{
                if(null != bis){
                    bis.close();
                }
                if(null != bos){
                    bos.close();
                }
            }catch(IOException e){
                System.out.println("下载文件失败,"+"文件路径:"+filePath+e);
                logger.error("文件下载失败!", e);
            }
        }
        //  返回值要注意,要不然就出现下面这句错误!
        //java+getOutputStream() has already been called for this response
        return null;
    }

 

原文地址:http://www.manongjc.com/article/17618.html