User-Profile-Image
hankin
  • 5
  • Java
  • Kotlin
  • Spring
  • Web
  • SQL
  • MegaData
  • More
  • Experience
  • Enamiĝu al vi
  • 分类
    • Zuul
    • Zookeeper
    • XML
    • WebSocket
    • Web Notes
    • Web
    • Vue
    • Thymeleaf
    • SQL Server
    • SQL Notes
    • SQL
    • SpringSecurity
    • SpringMVC
    • SpringJPA
    • SpringCloud
    • SpringBoot
    • Spring Notes
    • Spring
    • Servlet
    • Ribbon
    • Redis
    • RabbitMQ
    • Python
    • PostgreSQL
    • OAuth2
    • NOSQL
    • Netty
    • MySQL
    • MyBatis
    • More
    • MinIO
    • MegaData
    • Maven
    • LoadBalancer
    • Kotlin Notes
    • Kotlin
    • Kafka
    • jQuery
    • JavaScript
    • Java Notes
    • Java
    • Hystrix
    • Git
    • Gateway
    • Freemarker
    • Feign
    • Eureka
    • ElasticSearch
    • Docker
    • Consul
    • Ajax
    • ActiveMQ
  • 页面
    • 归档
    • 摘要
    • 杂图
    • 问题随笔
  • 友链
    • Spring Cloud Alibaba
    • Spring Cloud Alibaba - 指南
    • Spring Cloud
    • Nacos
    • Docker
    • ElasticSearch
    • Kotlin中文版
    • Kotlin易百
    • KotlinWeb3
    • KotlinNhooo
    • 前端开源搜索
    • Ktorm ORM
    • Ktorm-KSP
    • Ebean ORM
    • Maven
    • 江南一点雨
    • 江南国际站
    • 设计模式
    • 熊猫大佬
    • java学习
    • kotlin函数查询
    • Istio 服务网格
    • istio
    • Ktor 异步 Web 框架
    • PostGis
    • kuangstudy
    • 源码地图
    • it教程吧
    • Arthas-JVM调优
    • Electron
    • bugstack虫洞栈
    • github大佬宝典
    • Sa-Token
    • 前端技术胖
    • bennyhuo-Kt大佬
    • Rickiyang博客
    • 李大辉大佬博客
    • KOIN
    • SQLDelight
    • Exposed-Kt-ORM
    • Javalin—Web 框架
    • http4k—HTTP包
    • 爱威尔大佬
    • 小土豆
    • 小胖哥安全框架
    • 负雪明烛刷题
    • Kotlin-FP-Arrow
    • Lua参考手册
    • 美团文章
    • Java 全栈知识体系
    • 尼恩架构师学习
    • 现代 JavaScript 教程
    • GO相关文档
    • Go学习导航
    • GoCN社区
    • GO极客兔兔-案例
    • 讯飞星火GPT
    • Hollis博客
    • PostgreSQL德哥
    • 优质博客推荐
    • 半兽人大佬
    • 系列教程
    • PostgreSQL文章
    • 云原生资料库
    • 并发博客大佬
Help?

Please contact us on our email for need any support

Support
    首页   ›   Spring   ›   正文
Spring

SpringBoot—文件上传(StandardServletMultipartResolver )

2020-03-14 02:12:27
1212  0 0
参考目录 隐藏
1) 多文件上传:
2) java中File转为MultipartFile的四种方式

阅读完需:约 4 分钟

具体的理论:

SpringMVC—MultipartResolver 解析(文件上传)

首先在springboot里面StandardServletMultipartResolver是基本不需要配置的,因为有自动化配置了,而且springboot肯定满足servlet3.0的要求。

例子:

直接创建上传文件:

@RestController
public class FileUploadController {

    SimpleDateFormat s=new SimpleDateFormat("/yyyy/MM/dd/");//创建日期来分类
    @RequestMapping(value="/upload")
    public String upload(MultipartFile file , HttpServletRequest request )  {
        String format=s.format(new Date());
        String r=request.getServletContext().getRealPath("/img")+format;//获取根目录
        File folder=new File(r);//创建文件
        if(!folder.exists()){
            folder.mkdirs();
        }
        String oldname=file.getOriginalFilename();//获取旧的名字
        String newname= UUID.randomUUID().toString()+oldname.substring(oldname.lastIndexOf("."));
        //替换新的名字
        
        try {
            file.transferTo(new File(folder,newname));
            String url=request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+"/img"+format+newname;
            return url;//返回上传图片的路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }
}

基本上使用 StandardServletMultipartResolver 直接写上传文件的逻辑就可以了!

要注意的是上传的格式必须是POST,GET无法上传!!

编写html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交">
</form>
</body>
</html>

结果:

同样 StandardServletMultipartResolver 遵循着springboot的原则,如果你自定义了默认的配置就失效了,自定义也在 application.properties 里面。

多文件上传:

多文件只需要在单文件上修改一下就可以了

前端的html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/uploads" method="post" enctype="multipart/form-data">
    <input type="file" name="files" multiple>
    <input type="submit" value="提交">
</form>
</body>
</html>

在后端的FileUploadController 里增加一个新的方法:

 @RequestMapping(value="/uploads")
    public String uploads(MultipartFile[] files , HttpServletRequest request )  {
        String format=s.format(new Date());
        String r=request.getServletContext().getRealPath("/img")+format;//获取根目录
        File folder=new File(r);//创建文件
        if(!folder.exists()){
            folder.mkdirs();
        }
        for (MultipartFile file:files){
            String oldname=file.getOriginalFilename();//获取旧的名字
            String newname= UUID.randomUUID().toString()+oldname.substring(oldname.lastIndexOf("."));
            //替换新的名字

            try {
                file.transferTo(new File(folder,newname));
                String url=request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+"/img"+format+newname;
                System.out.println(url); //返回上传图片的路径
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "YES";
    }

只要将MultipartFile变成数组,并且用for循环去遍历就可以上传文件了

结果:

java中File转为MultipartFile的四种方式

因为在开发中需要调用其他人的上传文件接口,然而他们的接口文件上传参数类型是MultipartFile,所以需要转为MultipartFile类型

File转MultipartFile

方法一

<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
</dependency>
public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
            , MediaType.MULTIPART_FORM_DATA_VALUE
            , true
            , file.getName());
        try (InputStream input = new FileInputStream(file);
            OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

可以设置为静态方法,也可以使用对象进行调用

File file = new File("D:\\a.txt")
MultipartFile cMultiFile = getMultipartFile(file);

方法二

// 第二种方式
public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
            , MediaType.MULTIPART_FORM_DATA_VALUE
            , true
            , file.getName()
            , (int)file.length()
            , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

可以设置为静态方法,也可以使用对象进行调用

File file = new File("D:\\a.txt");
MultipartFile cMultiFile = getMultipartFile(file);

方法三

    public static FileItem createFileItem(String filePath, String fileName){
        String fieldName = "file";
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", false,fileName);
        File newfile = new File(filePath);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try (FileInputStream fis = new FileInputStream(newfile);
            OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192))!= -1)
            {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
File file = new File("D:\\a.txt");
FileItem fileItem = createFileItem(file.getPath(),file.getName());
MultipartFile cMultiFile = new CommonsMultipartFile(fileItem);

方法四

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
</dependency>

利用测试框架来模拟

import org.springframework.mock.web.MockMultipartFile;

File file = new File("D:\\a.txt");
MultipartFile cMultiFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));

如本文“对您有用”,欢迎随意打赏作者,让我们坚持创作!

0 打赏
Enamiĝu al vi
不要为明天忧虑.因为明天自有明天的忧虑.一天的难处一天当就够了。
543文章 68评论 294点赞 593737浏览

随机文章
JAVA对json操作—Jackson,Gson,fastjson
5年前
Freemarker常用指令
5年前
Ajax——用户注册
5年前
SpringBoot—AOP的用法
5年前
Spring—注解驱动开发Spring Ioc容器中注册Bean的7种方式
5年前
博客统计
  • 日志总数:543 篇
  • 评论数目:68 条
  • 建站日期:2020-03-06
  • 运行天数:1927 天
  • 标签总数:23 个
  • 最后更新:2024-12-20
Copyright © 2025 网站备案号: 浙ICP备20017730号 身体没有灵魂是死的,信心没有行为也是死的。
主页
页面
  • 归档
  • 摘要
  • 杂图
  • 问题随笔
博主
Enamiĝu al vi
Enamiĝu al vi 管理员
To be, or not to be
543 文章 68 评论 593737 浏览
测试
测试
看板娘
赞赏作者

请通过微信、支付宝 APP 扫一扫

感谢您对作者的支持!

 支付宝 微信支付