使用SpringMV自带的CommonsMultipartFile实现图片上传功能

说明

1.前端上传文件必须用表单上传

/**
     * 上传图片
     * 
     * @param params
     * @return
     */
    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    public @ResponseBody Map<String, Object> handleFileUpload(@RequestParam("file") CommonsMultipartFile file) {
        Map<String, Object> result = new HashMap<String, Object>();

        if (file == null) {
            result.put("code", 0);
            result.put("message", "文件不能为空");
            result.put("data", new HashMap<>());
        }
        FileItem item = file.getFileItem();
        String fileName = "";
        String fileSuffix = "";
        if (!item.isFormField()) {
            String name = item.getName();
            if (StringUtils.isNotEmpty(name)) {
                fileSuffix = name.substring(name.lastIndexOf(".") + 1, name.length());//获取文件后缀名
                fileName = CodeGenerator.getUUID() + "." + fileSuffix;//文件重命名,防止重复文件
            }
        }

        String bathPath = SysConfig.getPropertiesByKey("uploadPath");//硬盘上的路径
        String currentPath = "/image/" + CommonUtil.getUserId();
        String path = bathPath + currentPath;

        File dest = new File(bathPath + currentPath);
        if (!dest.exists()) {//目录不存在,创建目录
            dest.mkdirs();
        }

        System.out.println(path + fileName);
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(dest, fileName)));
                stream.write(bytes);
                stream.close();
                result.put("code", 1);
                result.put("message", "success");
                result.put("data", currentPath + "/" + fileName);
            } catch (Exception e) {
                result.put("code", 0);
                result.put("message", e.toString());
                System.out.println(e.toString());
                result.put("data", new HashMap<>());
            }
        } else {
            result.put("code", 0);
            result.put("message", "文件不能为空");
            System.out.println("文件不能为空");
            result.put("data", new HashMap<>());
        }

        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值