文件上传

一、源码

下面的文件上传适用于单个文件上传~

public String uploadFileMethod (MultipartFile multipartFile, HttpServletRequest request, String path) {
        // 若是文件上传的文件为空
        if (multipartFile.isEmpty()) {
            return "上传文件不能为空";
        }
        // 生成今日日期的文件目录
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String fileName = simpleDateFormat.format(new Date());
        File file = new File(path + fileName);
        // 文件临时位置
        System.err.println("文件位置:" + file.getAbsolutePath());
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        // 获取文件原始名称
        String oldName = multipartFile.getOriginalFilename();
        // 生成新文件名称
        String newName = UUID.randomUUID().toString().replace("-","") + oldName.substring(oldName.lastIndexOf("."));
        try {
            String basePath = file.getAbsoluteFile() + File.separator + newName;
            System.err.println("basePath:" + basePath);
            File newFile = new File(basePath);
            multipartFile.transferTo(newFile);
            String filePath = basePath;
            System.err.println("filePath:" + filePath);
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

文件上传成功后会返回文件上传位置

posted @ 2022-04-22 09:36  爱吃糖的橘猫  阅读(18)  评论(0编辑  收藏  举报