疑问求解

225 天前
 WolverineL

服务器写入文件

现在有这样一段代码

    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 没有权限吗?也没提示啊

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

473 次点击
所在节点    程序员
3 条回复
Giftina
225 天前
首先看看你的 storagePath 配的是啥,我感觉大概率是环境变量不同导致路径出了问题。

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

```
Path fileFilePath = Paths.get(storagePath, "image", fileName);
```
Giftina
225 天前
*小到斜杠正反问题
klo424
225 天前
也就是打印了 save img size:{},但是没打印 save img error:和 saveImgs error:?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/984915

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX