天天看点

springboot实现文件上传配置访问路径映射

1.配置yml

file:

  # 文件路径,使用jvm系统变量,兼容windows和linux;

  # profile: /img

  profile: E:/img

2.配置访问路径

@Configuration

public class UploadFilePathConfig  implements WebMvcConfigurer {

    @Value("${ruoyi.profile}")

    public String uploadFolder;

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("/image

    public static List<String> fileUploadImg(MultipartFile file) {

        String customPath = sdf.format(new Date());

        List<String> imgList = new ArrayList<String>();

        if (file != null && !file.isEmpty()) {

            // 获取文件名称

            String fileName = file.getOriginalFilename();

            if (fileName != null && fileName != "") {

                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

                // 获取访问网址拼接文件存放路径

                String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/files/img/";

                // 截取文件名后缀

                String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());

                // 重命名

                fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + fileF;

                String fileMulu = uploadFolder + "/" + customPath;

                Establish(fileMulu);

                File file1 = new File(fileMulu);

                // 保存文件

                File targetFile = new File(file1, fileName);

                try {

                    byte[] buffer = new byte[1024 * 1024];

                    InputStream is = file.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);

                    OutputStream os = new FileOutputStream(targetFile);

                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    int bytesRead = 0;

                    while ((bytesRead = bis.read(buffer, 0, 1024 * 1024)) != -1) {

                        bos.write(buffer, 0, bytesRead);

                        bos.flush();

                    }

                    bos.close();

                    bis.close();

                    os.close();

                    is.close();

                    String msg = returnUrl + customPath + "/" + fileName;

                    imgList.add(msg);

                } catch (Exception e) {

                    e.printStackTrace();

                }

            }

        }

        return imgList;

    }

    public static void Establish(String fileMulu) {

        File file = new File(fileMulu);

        if (!file.exists()){

            file.mkdirs();

        }

    }

}