• 请不要在回答技术问题时复制粘贴 AI 生成的内容
WolverineL
3.55D
0.29D
V2EX  ›  程序员

疑问求解

  •  
  •   WolverineL · Oct 24, 2023 · 898 views
    This topic created in 940 days ago, the information mentioned may be changed or developed.

    服务器写入文件

    现在有这样一段代码

        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 replies    2023-10-24 18:04:18 +08:00
    Giftina
        1
    Giftina  
       Oct 24, 2023
    首先看看你的 storagePath 配的是啥,我感觉大概率是环境变量不同导致路径出了问题。

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

    ```
    Path fileFilePath = Paths.get(storagePath, "image", fileName);
    ```
    Giftina
        2
    Giftina  
       Oct 24, 2023
    *小到斜杠正反问题
    v2er4241
        3
    v2er4241  
       Oct 24, 2023
    也就是打印了 save img size:{},但是没打印 save img error:和 saveImgs error:?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5400 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 03:45 · PVG 11:45 · LAX 20:45 · JFK 23:45
    ♥ Do have faith in what you're doing.