• 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;
        }
  • 相关阅读:
    curl 的使用,参数大全
    ubuntu 编译安装php5扩展
    ubuntu 编译安装 php5.6.40
    ubuntu 编译安装 mysql5.7.32
    ubuntu 编译安装 apache2.4.46
    Android 逆向工具总结
    mariadb 和 mysql 之间的版本关系
    ubuntu 使用 apt 安装 apache2 php7 mysql8
    linux 系统安装 pip
    P2756 飞行员配对方案问题 提交 13.91k 通过 7.59k 时间限制 1.00s 内存限制 125.00MB 返回题目
  • 原文地址:https://www.cnblogs.com/gczmn/p/9921479.html
Copyright © 2020-2023  润新知