SpringBoot如何实现文件上传功能

技术SpringBoot如何实现文件上传功能这篇文章主要介绍了SpringBoot如何实现文件上传功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。经典的

贺盛德贺盛德贺盛德跳船阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔阿叔,朱庇特谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯谢尼伯,范仲淹还是范仲淹,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,我的意思是,你是说.

经典的文件上传

不,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,我不知道,你好你好你好,嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨嗨。康伯坦(音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"音似"胸腺泡314演示一下,绿筠小姐胸腺泡菲兰达。

依赖关系

groupid rg。springframework。boot/groupid

artifactidpringr-boot starter-thmeleaf/artifactid

版本2 .5 .5/版本

/依赖哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟度级你是谁,吴亚玲!吴亚玲构建。格雷尔哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟:

编译组织。弹簧框架。靴子:弹簧靴启动器-thmeleaf 33336 2。5 '314行动起来你是说.

@RestController

@RequestMapping('/upload/*)

publicclassuploadaction

@ post apping(/file)

public objectuploadhandler(httpservletrequequest、Stringtitle、MultipartFilefile)>;

MapString,对象结果映射=newlink hashmap();

resultMap.put('title ',title);

resultMap.put('fileName,file。getname());//哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟

结果图。放('原始名称',文件。getriginalfilname());//嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯嚯

resultMap.put('content-type ',文件。get content type());//诶哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟

resultMap.put('fileSize ',文件。getsize()/1024 ' k ');//诶哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟哟

尝试[

//云娥

stringuploadedfilepath=保存文件(请求,文件。getinputstream()、file。getoriginalfilename()

nbsp。个

;.substring(file.getOriginalFilename().lastIndexOf(".") + 1));
            resultMap.put("uploadedFilePath", uploadedFilePath); // 文件大小
        } catch (IOException e) {
            System.err.println("error-path: /upload/file, message: " + e.getMessage());
        }
        return resultMap;
    }
    /**
     * 保存上传的文件到本地服务器
     *
     * @param request HttpServletRequest
     * @param input   输入流
     * @param ext     文件扩展名
     * @return 文件路径
     * @throws IOException
     */
    public String saveFile(HttpServletRequest request, InputStream input, String ext) throws IOException {
        String realPath = request.getServletContext().getRealPath("/upload/file/"); // 取得服务器真实路径
        File file = new File(realPath);
        if (!file.getParentFile().exists()) { // 目录不存在
            file.mkdirs(); // 创建多级目录
        }
        String filePath = realPath + UUID.randomUUID() + "." + ext;
        // 取的文件输出流
        OutputStream out = new FileOutputStream(filePath);
        byte[] data = new byte[2048]; // 缓冲数组2KB
        int len = 0; // 读取字节长度
        while ((len = input.read(data)) != -1) {
            out.write(data, 0, len); // 文件写入磁盘
        }
        if (input != null) {
            input.close();
        }
        out.close();
        return filePath;
    }
}

在resources目录下新建templates文件夹,在里面创建index.html文件作为项目首页展示。

<!doctype HTML>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>文件上传测试</title>
        <meta charset="UTF-8" />
    </head>
    <body>
        <form action="/upload/file" method="post" enctype="multipart/form-data">
            <span>标题:</span>
            <input type="text" name="title" /><br>
            <span>文件:</span>
            <input type="file" name="file" /><br>
            <input type="submit" value="上传"  />
        </form>
    </body>
</html>

启动项目,直接访问:http://localhost:8080/将进入index.html页面。

SpringBoot如何实现文件上传功能

点击上传按钮,文件将被保存到服务器磁盘中:

SpringBoot如何实现文件上传功能

SpringBoot对上传文件处理的简化

SpringBoot对FileUpload组件进行了整合,在文件保存的时候可以避免直接操作IO流,通过配置文件的方式指定文件上传的限制参数。修改application.yml文件:

server:
  port: 8080
spring:
  servlet:
    multipart:
      enabled: true  # 启用文件上传
      max-file-size: 1MB # 单文件上传最大限制
      max-request-size: 10MB # 文件上传最大值
      file-size-threshold: 10KB # 上传文件达到多大时写入磁盘
      location: / # 临时文件存储位置

修改UploadAction,使用MultipartFile类的transferTo方法保存上传文件。

@RestController
@RequestMapping("/upload/*")
public class UploadAction {
    @PostMapping("/file")
    public Object uploadHandler(HttpServletRequest request, String title, MultipartFile file) {
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("title", title);
        resultMap.put("fileName", file.getName()); // 文件名
        resultMap.put("originalFilename", file.getOriginalFilename()); // 原始名称
        resultMap.put("content-type", file.getContentType()); // 文件类型
        resultMap.put("fileSize", file.getSize() / 1024 + "K"); // 文件大小
        try {
            // 保存文件
            String etc = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String serverPath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() + request.getContextPath() + "/file/upload/";
            String fileName = UUID.randomUUID() + "." + etc;
            resultMap.put("filePath", serverPath + fileName); // 文件地址(服务器访问地址)
            // 文件保存再真实路径下
            File saveFile = new File(request.getServletContext().getRealPath("/file/upload/") + fileName);
            if (!saveFile.getParentFile().exists()) { // 目录不存在,创建目录
                saveFile.mkdirs();
            }
            file.transferTo(saveFile); // 保存上传文件
        } catch (IOException e) {
            System.err.println("error-path: /upload/file, message: " + e.getMessage());
        }
        return resultMap;
    }
}

访问:http://localhost:8080/

SpringBoot如何实现文件上传功能

点击上传按钮:

SpringBoot如何实现文件上传功能

在浏览器上访问filePath,可以预览上传的文件:

SpringBoot如何实现文件上传功能

感谢你能够认真阅读完这篇文章,希望小编分享的“SpringBoot如何实现文件上传功能”这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/91877.html

(0)

相关推荐

  • servlet和web应用服务器(servlet教程web)

    技术如何浅析Servlet的Web应用程序本篇文章给大家分享的是有关如何浅析Servlet的Web应用程序,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。Ja

    攻略 2021年12月18日
  • ADO.NET事务处理方法有哪些

    技术ADO.NET事务处理方法有哪些这篇文章主要介绍“ADO.NET事务处理方法有哪些”,在日常操作中,相信很多人在ADO.NET事务处理方法有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家

    攻略 2021年12月3日
  • 手把手教你提交Jar包到Maven公共仓库 | 萌新写开源02

    技术手把手教你提交Jar包到Maven公共仓库 | 萌新写开源02 手把手教你提交Jar包到Maven公共仓库 | 萌新写开源02本文,就整理一下我把项目上传到公共Maven仓库的过程,当做一篇教程文章

    礼包 2021年12月15日
  • 拉勾大前端高薪训练营全2021

    技术拉勾大前端高薪训练营全2021 拉勾大前端高薪训练营全2021(10).支持let与const在之前JS是没有块级作用域的,const与let填补了这方便的空白,const与let都是块级作用域。

    礼包 2021年11月1日
  • Golang如何打包配置文件

    技术Golang如何打包配置文件这篇文章主要介绍了Golang如何打包配置文件,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。背景最近在写一个涉及到管理阿里

    攻略 2021年12月11日
  • linux下怎么安装mysql

    技术linux下怎么安装mysql这篇文章主要介绍linux下怎么安装mysql,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!1、sudo apt-get install g++ gcc make

    攻略 2021年10月21日