springboot+MultipartFile文件上传,并设置项目访问的图片地址

1.在properties文件设置图片上传的最大值:

#   图片上传最大值
spring.servlet.multipart.max-file-size=3MB
spring.servlet.multipart.max-request-size=3MB

2.在properties文件配置文件访问地址:

#   图片上传真实路径
picture.upload.url=D:/workspace/upload/picture/
#   url访问路径
spring.mvc.static-path-pattern=/picture/**
#   图片存放真是路径
spring.resources.static-locations=file:D://workspace/upload/picture/
注意Linux和Windows上的目录结构不同

 

#   图片路径
picture.upload.url=/root/uploadFiles
#   url访问路径
spring.mvc.static-path-pattern=/picture/**
#   图片存放真是路径
spring.resources.static-locations=file://root/uploadFiles(该配置方法适用于图片上传地址和项目部署地址是同一台服务器,没有使用文件服务器,如果是文件服务器则用ftp方式去上传,文章不做举例)

@Value("${picture.upload.url}")
private String uploadUrl;
private static final String CONNECTURL = "picture";
上传controller
@Override
@PostMapping(value = "/file/upload", consumes = "multipart/form-data")
public Result fileUpload(MultipartFile file, String programId, String frameId, HttpServletRequest request) {
    if (StringUtils.isEmpty(programId) || StringUtils.isEmpty(frameId) || file.isEmpty()) {
        return Result.setResult(MessgeCode.PARAMETER_EMPTY);
    }
    String path = StringUtils.isEmpty(request.getContextPath()) ? "" : request.getContextPath() + "/";
    // 服务器访问地址
    String ipAndPortUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + path;
    String originNmae = file.getOriginalFilename();
    String fileName = frameId + originNmae.substring(originNmae.indexOf("."));//生成图片名称
    String realUrl = uploadUrl + programId + "/" + frameId + "/";
    try {
        FileUtil.uploadMethod(realUrl, fileName, file);
    } catch (Exception e) {
        e.printStackTrace();
        return Result.setResult(MessgeCode.UPLOAD_FAIL);
    }
    String url = ipAndPortUrl + CONNECTURL + "/" + programId + "/" + frameId + "/" + fileName;
    logger.info("访问路径" + url);
    return Result.setResult(MessgeCode.OK, url);
}
public class FileUtil {
    public static void uploadMethod(String fileUrl, String fileName, MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                File filepath = new File(fileUrl);
                if (!filepath.exists()) {
                    filepath.mkdirs();
                }
                // 文件保存路径
                String savePath = fileUrl + fileName;
                // 转存文件
                file.transferTo(new File(savePath));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

返回结果;http://187.33.2.2:8081/picture/11/110/110.png.

图片访问不需要JWT访问权限可以修改配置类:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf() // 由于使用的是JWT,我们这里不需要csrf
                .disable().sessionManagement()// 基于token,所以不需要session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                //暂时不需要登录 权限 TODO
                .antMatchers("/login/**").permitAll()
                .antMatchers("/picture/**").permitAll() // picture/**对应配置文件里面设置的映射地址
                .anyRequest().authenticated();
        // 禁用缓存
        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }
}

你可能感兴趣的:(Study)