基于springboot简单得文件上传

 文件上传

public String uploadFile(HttpServletRequest request, MultipartFile file, String fileName) {
        //避免重复去重
        String hash = EncryptUtil.encrypt(LocalDateTime.now().toString(),"date").substring(0,7);
        //图片访问的URI
        String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/static/imgs/";

            // 获取文件类型
            String originalFilename = "/"+hash+"_"+fileName;
            String path ="/opt/nginx/resources/";
            if(System.getProperty("os.name").startsWith("Windows")){
                path = "D:\\\\tmp\\file\\";
            }
            LocalDate date =  LocalDate.now();
            String  sDate = date.toString().replace("-","/");
            String savePath = path+sDate+originalFilename;

            File fileIn = new File(savePath);
            File filePath =  new File(path+sDate);
            if(!filePath.isDirectory()){
                filePath.mkdirs();
            }

            // 保存到服务器
        try {
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(fileIn);
                String projectPath = System.getProperty("user.dir");
                LOGGER.info("projectPath:{}",projectPath);
                String url= returnUrl + "/" + sDate+originalFilename;
                return url;
            } catch (IOException e) {
                LOGGER.info("服务器内部错误:" + originalFilename);
                e.printStackTrace();
            }

        return null;
    }

静态代理

继承WebMvcConfigurationSupport 

实现  
@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //swagger-ui代理
        registry.addResourceHandler("*.js").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        //图片代理
        String path ="/opt/nginx/resources/";
        if(System.getProperty("os.name").startsWith("Windows")){
            path = "D:\\\\tmp\\file\\";
        }
        registry.addResourceHandler("/static/imgs/**").addResourceLocations("file:".concat(path));
    }

 

你可能感兴趣的:(文件上传)