栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 文件上传

  1. 上传
    1.1 配置一个类
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**").addResourceLocations("file:D:\springboot\springboot_shop\img\");
    }
}

1.2 controller

 @RequestMapping("upload")
    public String upload(String uname , MultipartFile img) throws IOException { // 通过该请求可以去注册的页面
        System.out.println("uname...."+uname);
        System.out.println();
        String filename = img.getOriginalFilename() ;
        String path ="D:\Program Files\idea_workspace\springboot\springboot_shop\img";
        File file = new File (path,filename);
        img.transferTo(file);
        return "login";
    }

1.3 html

  

多文件上传
2.1 html 页面

2.2 controller

 @RequestMapping("upload")
    public String upload(String uname, HttpServletRequest request ) throws IOException { // 通过该请求可以去注册的页面
        System.out.println("uname...."+uname);
        System.out.println();
        List list = ((MultipartHttpServletRequest)request).getFiles("img");
        for(MultipartFile img : list){
            String filename = img.getOriginalFilename() ;
            String path ="D:\Program Files\idea_workspace\springboot\springboot_mybatis_html\img";
            File file = new File (path,filename);
            img.transferTo(file);
        }

        return "index";
    }
  1. 下载
    3.1 下载地址
 下载该图片

3.2 pom 配置


            commons-fileupload
            commons-fileupload
            1.3.1
        

3.3 controller

@RequestMapping("/download")
    public ResponseEntity download(@RequestParam("fileName") String fileName, HttpServletRequest req)
            throws IOException {

        // 获取文件存放的真实路径
        //String realPath="D:\Program Files\idea_workspace\ssm_ajax_down_upload\ssm_ajax_down_upload\images";
        String realPath ="D:\springboot\springboot_mybatis_html\img";

        //创建文件实例
        File file = new File(realPath, fileName);
        //修改文件名的编码格式
        String downloadFileName = new String(fileName.getBytes("UTF-8"), "UTF-8");

        //设置httpHeaders,使浏览器响应下载
        HttpHeaders headers = new HttpHeaders();
        //告诉浏览器执行下载的操作,“attachment”告诉了浏览器进行下载,下载的文件 文件名为 downloadFileName
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //设置响应方式为二进制,以二进制流传输
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318978.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号