java jdk11 文件流上传

代码调用示例,适用于小文件通过文件流上传

        try {
            String filename = null;
            // String baseUrl = "files/***/";
            if (userType.equals(UserTypeEnum.TEACHER.getKey())) {
                // filename = "operation_tea.pdf";
                filename = opeTeaFilename;
            } else if (userType.equals(UserTypeEnum.STUDENT.getKey())) {
                // filename = "operation_stu.pdf";
                filename = opeStuFilename;
            } else if (userType.equals(UserTypeEnum.ADMIN.getKey())){
                // filename = "operation_adm.pdf";
                filename = opeAdmFilename;
            } else {
                log.error("用户类型错误,下载用户操作手册失败!");
                throw new SysException(SysMessage.REQUEST_PARAMS_INVALIDATE);
            }
            // String path = baseUrl + filename;
            // File file = new File(path);
            // File file = new File(baseUrl, filename);
            // InputStream fileInputStream = new FileInputStream(file);
            // InputStream fileInputStream = Files.newInputStream(file.toPath());
            InputStream fileInputStream = Files.newInputStream(Paths.get(baseUrl, filename));

            InputStreamResource irs = new InputStreamResource(fileInputStream);
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header("Content-disposition", "attachment; filename=***.pdf")
                    .body(irs);
        } catch (Exception e) {
            log.error("操作手册文件下载异常:{},{}", e.getMessage(), e);
            throw new SysException(SysMessage.FILE_DOWNLOAD_FAIL);
        }

你可能感兴趣的:(java,servlet,开发语言)