spring boot上传图片or文件和注意事项

以上传图片为例,废话不多说,直接上代码

//上传图片到文件夹or服务器文件夹并返回图片路径
    public String addBenDiImg(MultipartFile file) {
        String objectPath = "group1/M00/00/21/";

        String path = null;// 文件路径

        if (file != null) {// 判断上传的文件是否为空
            String type = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称

            // 判断文件类型
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            if (type != null) {// 判断文件类型是否为空

                if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) {

                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    fileName = uuid + "." + type;
                    System.out.println("文件名称:" + fileName);

                    //服务器文件夹绝对路径
                    path = "xxx/group1/M00/00/21/";

                    File desc = new File(path);
                    if (!desc.exists()) {
                        desc.mkdirs();
                        log.info("创建文件夹,说明路径非绝对路径或者服务器没有这个文件夹");
                    }

                    try {
                        File newFile = new File(desc.getAbsolutePath() + File.separator + fileName);
                        file.transferTo(newFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.error(e.getMessage());
                        return "上传异常";
                    }

                    System.out.println("文件成功上传到指定目录下");
                    //放到服务器中则还需要拼接项目前缀+图片地址: http://xxx.com+服务器文件夹绝对路径+图片名
                    return objectPath + fileName;
                }

            } else {
                return "不是我们想要的文件类型,请按要求重新上传";
            }
        } else {
            return "文件类型为空";
        }
        return "已经成功上传到指定目录";
    }

需要注意:上传关键代码就两行行:

File newFile = new File(desc.getAbsolutePath() + File.separator + fileName);

file.transferTo(newFile);

但是!在这之前newFile的参数一定只能用:上面的方式来创建!

以下是错误创建方式,以上述代码为例子:

File newFile = new File(path+fileName);

这样做代码可以编译和运行成功,但图片或文件并不会成功上传并且保存在文件夹中

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值