springboot实现图片上传

本文介绍了如何利用layui开发按钮,通过modelAttribute处理编辑数据,配置Spring MVC的文件存储路径,实现上传图片并解决跨域和访问路径问题。同时,探讨了如何在Spring Security中管理图片访问权限,确保富文本编辑器的正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用layui的组件实现按钮

2.使用modelAttribute注解实现数据的传入(这个是点击编辑后有了这个对象实例)

@Controller
@RequestMapping("/a/film")
public class FilmController{
//只要访问路径中有id值的传入就会执行这个方法返回一个Film对象
@ModelAttribute("film")
public Film get(Integer id){
    if(id!=null){
       return filmService.getById(id);
 }else{
return new Film();
}}
*****************
下边以后的所有类中都能使用这个Film
}

3.在application.yml文件中定义文间存储的本地路径

#定义图片存储的位置
system:
  filePath: D:\image\cms1010
  #图片访问路径,因为富文本编辑器中的图片必须使用这种url才能实现回显
  urlPath: http://localhost:8080/cms

设置一个配置类来对应yml文件中的值(方便取值)

@Data
@Component
@ConfigurationProperties(prefix="system")  //这个prefix对应yml文件中
public class AppConfig{
    private String filePath;//文件存储路径
    private String urlPath;//文件访问路径

}

3.实现上传图片文件控制器

@RestController
@RequestMapping("/a/upload")
public class UploadFileController {
    @Autowired
    private AppConfig appConfig;

    @RequestMapping("/file")
    public FileResult fileUpload(MultipartFile file) {
        String fileName = "";
        if (!file.isEmpty()) {
            //获取文件的后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            //定义新文件的名字
            fileName = System.currentTimeMillis() + suffix;

            //定义文件存储的最终路径
            String savePath = appConfig.getFilePath() + "/film/" + fileName;

            File dest = new File(savePath);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);//保存文件
            } catch (IOException e) {
                e.printStackTrace();
                return new FileResult("300", "文件上传失败");
            }
        } else {
            return new FileResult("300", "文件上传失败");
        }

        //将上传成功后的文件路径返回到前端
        String fileVisitPath = appConfig.getUrlPath() + "/public/film/" + fileName; //为了在富文本编辑器中使用
        String filePath = fileName;//存表中

        List<String> list = new ArrayList<>();
        list.add(fileVisitPath);
        list.add(filePath);
        return new FileResult("200", list);//返回到前端读取数据

    }
}

4.现在图片可以保存,但是访问是有问题的,因为没有设置虚拟访问路径来访问本地文件

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //默认的访问页面 /user/index
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/a", "/a/user/login");//后台路径
        registry.addRedirectViewController("/f", "/f/film/index");//前台路径
    }

    //配置图片的访问路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //访问路径: http://localhost:9000/cms/public/film/xxx.jpg
        registry.addResourceHandler("/public/**").addResourceLocations("file:/D:/image/cms1010/");
    //访问路径对应的本地路径
    }
}

虽然设置了访问路径和本地路径的关联,但是我是用的springSecurity,需要对该路径放行

@Configuration
@EnableWebSecurity //开启spring security功能
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    SessionRegistry sessionRegistry;

    @Bean
    public SessionRegistry getSessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }

    //使用注解在配置类中直接实例化对象
    @Bean
    UserDetailsService customUserService() {
        return new CustomUserService();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //解决Refused to display 'http://localhost:9000/cms/a/console' in a frame because it set 'X-Frame-Options' to 'deny'.
        http.headers().frameOptions().disable();//解决不能加载iframe
        http.csrf().disable(); //解决跨域的问题
        http
                .authorizeRequests()    //验证请求
                .antMatchers("/assets/**", "/js/**", "/public/**", "/front/**").permitAll() //放行部分合法路径
                .antMatchers("/f/**").permitAll() //放行部分合法路径
                .anyRequest().authenticated() //任何请求,登录后可以访问
                .and()
                .formLogin()
                .loginPage("/a/user/login")
                .defaultSuccessUrl("/a/index", true) //登录成功的默认跳转路径
                .failureUrl("/a/user/login?error") //登录失败的跳转路径
                .permitAll() //登录页面用户任意访问
                .and()
                .logout().permitAll().invalidateHttpSession(true)
                .and().sessionManagement().maximumSessions(10).expiredUrl("/a/user/login"); //注销行为任意访问
    }

    //AuthenticationManagerBuilder验证前台提交的数据
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //BCryptPasswordEncoder指定密码的验证规则
        ////使用数据库认证,参数为一个UserService类型的对象
        auth.userDetailsService(customUserService()).passwordEncoder(new BCryptPasswordEncoder());
    }
}

5.wangdeitor富文本编辑器中的

富文本编辑器只能使用前边返回result的第一个参数,不能在前端自己拼接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戏子☜已入画@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值