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;
    }

 

转载于:https://www.cnblogs.com/memoryXudy/p/8709533.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值