基于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));
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值