SpringBoot文件上传、删除及下载

SpringBoot文件上传、删除及下载

最近的项目中,需要将文件保存项目的根目录路径下,特此记录下文件的操作:

文件上传

    /**
     * 文件上传(相对路径)
     *
     * @param uploadFile 文件
     * @param request    参数
     * @return 文件路径
     */
    public static String upload(MultipartFile uploadFile, HttpServletRequest request) {
        // 项目根路径下的目录
        final String UPLOAD_PATH_PREFIX = "/static/resources/upload/app";
        //访问目录
        final String DOWNLOAD_PATH_PREFIX = "/resources/upload/app";
        if (uploadFile.isEmpty()) {
            //返回选择文件提示
            return "请选择上传文件";
        }
        //项目根目录的绝对路径 + 指定文件夹路径
        String realPath = System.getProperty("user.dir") + UPLOAD_PATH_PREFIX;
        logger.info("-----------上传文件保存的路径【" + realPath + "】-----------");
        //存放上传文件的文件夹
        File file = new File(realPath);
        logger.info("-----------输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径【" + file.getAbsolutePath() + "】-----------");
        if (!file.isDirectory()) {
            //递归生成文件夹
            file.mkdirs();
        }
        //获取原始的名字
        String oldName = uploadFile.getOriginalFilename();
        logger.info("-----------文件原始的名字【" + oldName + "】-----------");
        //原文件名 + 时间戳 + 文件类型
        String newName = oldName.substring(0, oldName.lastIndexOf(".")) + System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf("."));
        logger.info("-----------文件要保存后的新名字【" + newName + "】-----------");
        try {
            //构建真实的文件路径
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //转存文件到指定路径,如果文件名重复的话,将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
            uploadFile.transferTo(newFile);
            //访问前缀方式一
//            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + DOWNLOAD_PATH_PREFIX + "/"  + newName;
            //访问前缀方式二
//            StringBuffer url = request.getRequestURL();
//            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
            //不包含访问前缀
            String filePath = DOWNLOAD_PATH_PREFIX + "/" + newName;
            logger.info("-----------【" + filePath + "】-----------");
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败!";
    }

文件删除

    /**
     * 文件删除
     * 
     * @param filePath 文件路径
     * @return false、true
     */
    public static Boolean delete(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
            System.out.println("===========删除成功=================");
            return true;
        } else {
            System.out.println("===============删除失败==============");
            return false;
        }
    }

文件下载

文件下载功能参考博客:https://www.jianshu.com/p/85017f5ecba1

/**
* 文件下载
*
* @param response 声明response
* @return false、true
*/
public Boolean downloadFile(HttpServletResponse response) {
    String fileName = "redis-serve1599809147700.exe";// 文件名
    if (fileName != null) {
        //设置文件路径
        File file = new File(System.getProperty("user.dir") + "/static/resources/upload/app/redis-serve1599809147700.exe");
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return false;
}
自我控制是最强者的本能-萧伯纳
原文地址:https://www.cnblogs.com/CF1314/p/13665817.html