springboot实现文件上传到服务器上,并通过url访问

发布于:2025-03-21 ⋅ 阅读:(39) ⋅ 点赞:(0)

1,文件存储

外部用户可通过url访问服务器资源文件resources目录下的静态资源,但若是将上传的文件都保存在resources相关目录下,将会导致后续打包过大,程序和代码不分离,无法查看等问题。
解决方案:
文件上传到服务器某个目录,然后SpringBoot配置虚拟路径,映射到此目录。

2,访问问题

通过WebMvcConfigurer 的addResourceHandlers将匹配上虚拟路径的url映射到文件上传到服务器的目录,这样就可以通过url来获取服务器上的静态资源了。

3,详细步骤

(1)配置类
public class WebMvcConfiguration implements WebMvcConfigurer {
    
    @Autowired
    HandleReportServiceImpl fileService;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将匹配上/files/**虚拟路径的url映射到文件上传到服务器的目录,获取静态资源
        registry.addResourceHandler("/" + fileService.pathPattern + "/**").addResourceLocations("file:" + fileService.filePath);
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }

}

(2)Controller类
    @ApiOperation(value = "上传模板", notes = "", response = String.class)
    @PostMapping("/upload")
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session){
        return handleReportService.uploadReport(file,session);
    }
(3)Service类
@Service
public class HandleReportServiceImpl implements HandleReportService {

    @Value("${upload.uploadPath}")
    private String uploadPath;

    public String pathPattern = "files";

    private static final String fileDir = "fileStorage";

    public String filePath = System.getProperty("user.dir") + File.separator + fileDir + File.separator;


    @Override
    public Object uploadReport(MultipartFile file, HttpSession session) {
        return upload(file,session);
    }

    public Object upload(MultipartFile file,HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        map.put("flag", true);
        String name = file.getOriginalFilename();
        //限制上传的文件,通过判断后缀的方式
        String fileF = name.substring(name.lastIndexOf("."));//文件后缀
        if (!(".docx".equals(fileF))) {
            map.put("flag", false);
            map.put("message", "请上传docx格式的文件!");
            return map;
        }
        String pathTemp = filePath + getDate() + "/";
        String filePaths = pathTemp + name;
        File f = new File(pathTemp);
        if (!f.exists()) {
            f.mkdirs();
        }
        File s = new File(filePaths);
        //直接上传
        try {
            file.transferTo(s);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("flag", false);
            map.put("message", "上传失败,详细信息为:" + e.getMessage());
            return map;
        }
        map.put("message", "上传成功");
        map.put("path", filePaths);
        return map;
    }

会上传到项目根目录下的fileStorage目录下,如果是jar包会在jar包同目录下创建fileStorage

(4)最后通过http://localhost:8080/files/文件名访问。