Java 文件本地上传、下载和预览的实现

  以下方法为通用版本 实测图片和pdf 都没有问题 上传方法需要前端配合post请求 ,下载前端用a标签就可以,预览 前端使用ifrme标签   ,就可以实现基本功能。。。

1、文件本地上传

public String uploadFile(@RequestParam("file") Part file, @RequestParam(value = "dirPath", required = false) String dirPath) throws IOException {
        String fileName = file.getSubmittedFileName();//项目路径
        String dir = ConversionFactoryUtil.modulePath(dirPath == null ? "File" : dirPath);
        File dateDir = new File(dir);
        if (!dateDir.exists()) {
            dateDir.mkdirs();
        }
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String fName = UUID.randomUUID().toString().replace("-", "");
        String filePath = File.separator + dir + File.separator + fName + "." + prefix;
        InputStream inputStream = file.getInputStream();
        Files.copy(inputStream, Paths.get(ConversionFactoryUtil.rootPath() + filePath));
        Map<String, String> result = new HashMap<>();
        result.put("fileName", fileName);
        result.put("filePath", filePath);
        return gson.toJson(result);
    }

2、文件本地下载

public String downLoadFile(String filePath, HttpServletResponse res, HttpServletRequest request) {
        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
        try {
        res.setContentType("application/doc");
        final String userAgent = request.getHeader("USER-AGENT");
        if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
            fileName = URLEncoder.encode(fileName,"UTF-8");
        }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        }else{
            fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
        }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 通知浏览器以附件形式下载
        res.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os;
        try {
            os = res.getOutputStream();
            File file = new File(ConversionFactoryUtil.rootPath() + File.separator + filePath);
            if (file.exists()) {
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                    i = bis.read(buff);
                }
                return "success";
            } else {
                System.out.println("file not exists ...filePath:" + filePath);
                return "file not local exists ...";
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

3、文件本地预览

public String previewFile(String filePath, HttpServletResponse res, HttpServletRequest request) {
        String fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
        try {
            res.setContentType("application/doc");
            final String userAgent = request.getHeader("USER-AGENT");
            if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                fileName = URLEncoder.encode(fileName,"UTF-8");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
            }
            res.reset();// 非常重要
            res.setHeader("Content-Disposition", "inline; filename=" + fileName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        File file = null;
        try {
            os = res.getOutputStream();
             file = new File(ConversionFactoryUtil.rootPath()  + filePath);
            if (file.exists()) {
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, i);
                    os.flush();
                    i = bis.read(buff);
                }
                return "success";
            } else {
                return "file not local exists ...";
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    os.close();
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

 

posted @ 2018-04-03 16:53  Mr.DongYang  阅读(2385)  评论(0编辑  收藏  举报