Java图片上传

话不多说直接上代码

1前台通过name是images的file框选择后进入controller

	@RequestMapping(value = "/image/save-test",method = RequestMethod.POST)
    public String saveImg(@RequestParam("images") MultipartFile file)throws Exception {
        String pathname = "";
        String returnPath = "";
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        File path = new File(ResourceUtils.getURL("classpath:").getPath());//获取Spring boot项目的根路径,在开发时获取到的是/target/classes/
        String absolutePath = path.getAbsolutePath();
        System.out.println("path.getAbsolutePath()++++"+path.getAbsolutePath());
        File uploadFile = new File(path.getAbsolutePath(), "static/images/");//开发测试模式中 获取到的是/target/classes/static/images/
        System.out.println(uploadFile.getPath());
        if (!uploadFile.exists()){//如果文件不存在则创建
            uploadFile.mkdirs();
        }
        //获取文件后缀名
        String end=fileName.substring(fileName.length()-3,fileName.length());

        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        //图片名称 采取时间拼接随机数
        String name = df.format(new Date());
        Random r = new Random();
        for(int i = 0 ;i < 3 ;i++){
            name += r.nextInt(10);
        }
        returnPath = name + "." +end; //目标文件的文件名
        String url="D:\\APP\\Hbuilde存储地址\\human\\spz\\images";
        pathname = url+ "\\" + returnPath;
        System.out.println("555555555"+pathname);

        file.transferTo(new File(pathname));//文件转存
        return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值