暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

springboot单/多文件上传

JAVA不归路 2021-09-09
615

springboot文件上传

多文件上传

简单的form表单

<form action="/upload"  method="post" enctype="multipart/form-data">
            文件1<input type="file" name="files">
            文件2<input type="file" name="files">
            文件3<input type="file" name="files">
    <input type="submit" value="tijiao">
</form>

controller层

    @RequestMapping("/upload")
    public String totest1(MultipartFile[] files) throws Exception {
        String path = "E:/upload/";//设置文件放置位置
         File f = new File(path);
        if(!f.exists()){f.mkdirs();}//没有该文件就创建
        //判断file数组不能为空并且长度大于0
        if(files!=null&&files.length>0){
            //循环获取file数组中得文件
            for(int i = 0;i<files.length;i++){
                //获取UUID
                String uuid = UUID.randomUUID().toString().replaceAll("-""");
                MultipartFile file = files[i];
                String filename = uuid+ file.getOriginalFilename();//获取文件名字
                file.transferTo(new File(f,filename));//上传文件
            }
        }

        return "test";
    }

单文件上传(上传到项目中)

简单的form表单

<form action="/upload"  method="post" enctype="multipart/form-data">          
            文件3<input type="file" name="file">
    <input type="submit" value="tijiao">
</form>

创建MyMvcConfig类配置资源映射

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       //静态资源(图片)映射/表访问该路径会映射到磁盘的某个文件
      String path ="F:/testProject/newblog/mybolg/src/main/resources/static/uploadimg/";//项目放置文件路径
      registry.addResourceHandler("/uploadimg/**").addResourceLocations("file:"+path);
    }
}

controller层

 @RequestMapping("/upload")
    public String totest1(MultipartFile file) throws Exception {
         String filename = uuid+ file.getOriginalFilename();//获取文件名字
                                //项目放置文件路径  
        File fileDir = new File("mybolg/src/main/resources/static/uploadimg");
        if(!fileDir.exists()){fileDir.mkdirs();}  //创建存放路径
        file.transferTo(new File(fileDir.getAbsolutePath(),filename));//上传文件
        String path = "/uploadimg/"+filename;//获取文件存储的相对路径,存储到相应对象中
        return "test";
    }

thymeleaf小技巧

下拉/多选框回显后台数据

<option th:selected="${category.cate_name} eq ${cg.getCate_name()}"  th:each="cg:${allcate}" th:value="${cg.getCate_name()}">[[${cg.getCate_name()}]]</option>
th:selectd="" 返回boolean值,返回true则有seleced属性,返回false则没有
checked等其他属性都可以这样使用


文章转载自JAVA不归路,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论