V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
WolverineL
V2EX  ›  程序员

疑问求解

  •  
  •   WolverineL · 204 天前 · 468 次点击
    这是一个创建于 204 天前的主题,其中的信息可能已经有所发展或是发生改变。

    服务器写入文件

    现在有这样一段代码

        private void saveImgs(MultipartFile[] images, FirePoint firePoint) {
            for (MultipartFile file : images) {
                new Thread(()->{
                    try {
                        VideoFireImagePO image = new VideoFireImagePO();
                        String fileName = file.getOriginalFilename();
                        image.setAlarmId(firePoint.getId().toString());
                        image.setFileName(fileName);
                        try {
                            log.info("save img:{}", fileName);
                            String fileFilePath = storagePath + "image/" + fileName;
                            image.setImagePath(fileFilePath);
    
                            File img = new File(fileFilePath);
                            if (!img.getParentFile().exists()){
                                img.getParentFile().mkdirs();
                            }
                            byte[] bytes = file.getBytes();
                            log.info("save img size:{}", bytes.length);
                            OutputStream out = new FileOutputStream(fileFilePath);
                            out.write(bytes);
                            out.flush();
                            out.close();
                            log.info("save img success: {}", fileName);
                        } catch (IOException e) {
                            log.error("save img error: ", e);
                        }
                        videFireImageMapper.insert(image);
                    }catch (Exception e){
                        log.error("saveImgs error: ", e);
                    }
                }).start();
            }
        }
    

    往服务器写入文件 首先本地测试没问题 发布服务器就死活写不进去还没报错 路径没问题,文件也上传了 bytes 不为 0 没有权限吗?也没提示啊

    有没有大佬帮忙分析下,困扰许久

    3 条回复    2023-10-24 18:04:18 +08:00
    Giftina
        1
    Giftina  
       204 天前
    首先看看你的 storagePath 配的是啥,我感觉大概率是环境变量不同导致路径出了问题。

    此外不建议这种直接用字符串来拼接路径的方式,这太硬核了,很容易出问题,小到斜杠,大到注入都能给你整出来。用 paths.get() 去处理是很正规的方式。

    ```
    Path fileFilePath = Paths.get(storagePath, "image", fileName);
    ```
    Giftina
        2
    Giftina  
       204 天前
    *小到斜杠正反问题
    klo424
        3
    klo424  
       204 天前
    也就是打印了 save img size:{},但是没打印 save img error:和 saveImgs error:?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   6251 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 01:53 · PVG 09:53 · LAX 18:53 · JFK 21:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.