栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

文件上传到服务器本地

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件上传到服务器本地

项目需要做一个模板管理,由于模板内容不多,所以并不使用Nginx和FTP和OSS管理,采用最朴素的文件上传到本地服务器中。

Controller层
    
    @Operation(tags = "文件模版表", summary = "上传模板到相对路径")
    @PostMapping("/upload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件"),
            @ApiImplicitParam(name = "code", value = "文件code唯一")
    })
    public Result upload(MultipartFile file, String code){
        return templateService.uploadTemplate(file, code);
    }


    
    @GetMapping(value = "file")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "文件code")
    })
    public void file(String code, HttpServletResponse response) throws IOException {
        templateService.getFile(code, response);
    }
Service
    
    Result uploadTemplate(MultipartFile file,String code);

    
    void getFile(String code, HttpServletResponse response) throws IOException;
ServiceImpl
    @Override
    public Result uploadTemplate(MultipartFile file, String code) {
        // 获取项目根目录
        String property = null;
        try {
            property = new File(ResourceUtils.getURL("classpath:").getPath()).getParent();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 判断code是否已经存在
        Template template = templateMapper.selectOne(Wrappers.lambdaQuery(Template.class)
                .eq(Template::getDeleted, false)
                .eq(Template::getCode, code));
        if (Objects.nonNull(template)) {
            throw new ApplicationException(500, code + "模板已存在");
        }

        // 获取文件后缀名
        String substring = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        try {

            //完成入库操作
            Template build = Template.builder().code(code)
                    .name(file.getOriginalFilename())
                    .extension(substring)
                    .path( this.path + code + substring)
                    .build();
            templateMapper.insert(build);
            savePic(file.getInputStream(), code + substring, property + this.path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success();
    }
    @Override
    public void getFile(String code, HttpServletResponse response) throws IOException {
       String  property = new File(ResourceUtils.getURL("classpath:").getPath()).getParent();
        // 通过文件id查询模板文件
        Template template = templateMapper.selectOne(Wrappers.lambdaQuery(Template.class)
                .eq(Template :: getCode,code)
                .eq(Template :: getDeleted ,false));
        if (Objects.isNull(template)) {
            throw new ApplicationException(500, "模板不存在");
        }

        // 读到流中
        InputStream inStream;
        try {
            inStream = new FileInputStream(property + template.getPath());
            // 设置输出的格式
            response.reset();
            response.setContentType("application/octet-stream");
            String filename = URLEncoder.encode(template.getName(), StandardCharsets.UTF_8);
            response.addHeader("Content-Disposition", "attachment; filename=" + filename);
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
    
    
    private void savePic(InputStream inputStream, String code, String property) {
        // 获取项目根目录
        OutputStream os = null;
        try {

            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            int len;

            // 输出的文件流保存到本地文件
            File tempFile = new File(property);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }

            // 用code保存文件名
            os = new FileOutputStream(tempFile.getPath() + File.separator + code);

            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕,关闭所有链接
            try {
                assert os != null;
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/460963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号