SpringBoot上传图片

该博客主要介绍了如何处理MultipartFile类型的文件上传,通过生成UUID作为文件名,避免重复,并将其保存到指定目录。同时,提供了获取静态资源路径的方法,确保文件能够正确存储和访问。在遇到IOException时,进行了错误处理。
摘要由CSDN通过智能技术生成
	 /**
     * 上传图片
     * @param file
     * @return
     */
    @Override
    public String fileUpload(MultipartFile file) {
        //设置文件名,如:ef931b6f-ce9e-49e8-a357-e52c4fc912f7.jpg
        String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		//System.out.println(uploadDirectory());
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadDirectory() + "/" + fileName);
            //写入文件
            Files.write(path, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回前端
        String filename = "../images/" + fileName;
        return filename;
    }

    /**
     * 获取static/images/的绝对路径
     * @return
     * @throws FileNotFoundException
     */
    public String uploadDirectory() throws FileNotFoundException {
        File path = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!path.exists()) {
            path = new File("");
        }
        File upload = new File(path.getAbsolutePath(), "static/images/");
        if (!upload.exists()) {
            upload.mkdirs();
            System.out.println(upload.getAbsolutePath());
        }
        return upload.getAbsolutePath();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值