springboot使用MultipartFile上传文件以及File与MultipartFile互转

2023-05-16

    如下所示的代码,是一个在springboot项目中使用MultipartFile进行文件上传的示例:

package com.springboot.web;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class UploadController {

    private String path = "d:/temp";

    @PostMapping("/upload")
    public ResponseEntity upload(MultipartFile file) {
        Map<String,Object> res = new HashMap<>();
        try {
            File outFile = new File(path.concat(File.separator).concat(file.getOriginalFilename()));
            file.transferTo(outFile);
            res.put("url",outFile.getAbsolutePath());
            res.put("code",200);
        } catch (Exception e) {
            e.printStackTrace();
            res.put("msg","upload fail");
            res.put("code",500);
        }
        return ResponseEntity.ok(res);
    }
}

    我们在前端页面上,进行配置上传的时候,可以使用这样的form:

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

    这里需要注意的是,前端的元素<input type="file" name="file"/>这里的name属性,它要和后端接口里面MultipartFile file参数名字对应起来。否则,接口会报空指针异常。

    现在web一般流行的是异步上传,所以使用三方javascript框架的时候,也需要注意,这里代表file的属性名一定要指定为file,与接口中参数file名字对应起来。

    到这里,使用MultipartFile上传文件基本就完成了,但是,我们这种接口有一个问题,如果我们使用三方服务来调用这个接口,那么这个参数MultipartFile还不好传递,因为这个类型是一个接口类型:

public interface MultipartFile extends InputStreamSource {
    String getName();

    @Nullable
    String getOriginalFilename();

    @Nullable
    String getContentType();

    boolean isEmpty();

    long getSize();

    byte[] getBytes() throws IOException;

    InputStream getInputStream() throws IOException;

    default Resource getResource() {
        return new MultipartFileResource(this);
    }

    void transferTo(File dest) throws IOException, IllegalStateException;

    default void transferTo(Path dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
    }
}

    如果java后端来写这个接口调用,我们本地的文件File有的是,问题是怎么把这个File转为MultipartFile,有一种办法就是借助spring-test依赖下的MockMultipartFile类型,代码如下所示:

package com.springboot.web;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.io.File;
import java.io.FileInputStream;

@SpringBootTest
@RunWith(SpringRunner.class)
public class UploadControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void upload() {
        FileInputStream inputStream = null;
        File file = new File("c:\\users\\buejee\\pictures\\avatar.png");
        try {
            inputStream = new FileInputStream(file);
            MockMultipartFile multipartFile = new MockMultipartFile(
                    "file",
                    file.getName(),
                    "APPLICATION_OCTET_STREAM",
                    inputStream);
            MvcResult result = mockMvc.perform(
                    MockMvcRequestBuilders
                    .fileUpload("/test/upload")
                    .file(multipartFile))
                    .andExpect(MockMvcResultMatchers.status().isOk())
                    .andReturn();
            String response = result.getResponse().getContentAsString();
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

    这里的核心代码就是这几行:

FileInputStream inputStream = null;
File file = new File("c:\\users\\buejee\\pictures\\avatar.png");
inputStream = new FileInputStream(file);
MockMultipartFile multipartFile = new MockMultipartFile(
                    "file",
                    file.getName(),
                    "APPLICATION_OCTET_STREAM",
                    inputStream);

    在构造MockMultipartFile的时候,我们传入的第一个参数就是file,这个还是上面说的,需要和接口中MultipartFile file参数的名称对应起来。

    如果不想使用spring-test依赖下的MockMultipartFile,那么就只能自定义一个MultipartFile的实现,其实实现过程完全可以参考MockMultipartFile:

public class MockMultipartFile implements MultipartFile {
    private final String name;
    private final String originalFilename;
    @Nullable
    private final String contentType;
    private final byte[] content;

    public MockMultipartFile(String name, @Nullable byte[] content) {
        this(name, "", (String)null, (byte[])content);
    }

    public MockMultipartFile(String name, InputStream contentStream) throws IOException {
        this(name, "", (String)null, (byte[])FileCopyUtils.copyToByteArray(contentStream));
    }

    public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, @Nullable byte[] content) {
        Assert.hasLength(name, "Name must not be empty");
        this.name = name;
        this.originalFilename = originalFilename != null ? originalFilename : "";
        this.contentType = contentType;
        this.content = content != null ? content : new byte[0];
    }

    public MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream) throws IOException {
        this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream));
    }

    public String getName() {
        return this.name;
    }

    @NonNull
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Nullable
    public String getContentType() {
        return this.contentType;
    }

    public boolean isEmpty() {
        return this.content.length == 0;
    }

    public long getSize() {
        return (long)this.content.length;
    }

    public byte[] getBytes() throws IOException {
        return this.content;
    }

    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileCopyUtils.copy(this.content, dest);
    }
}

    构造出了MultipartFile实例,那么调用上传接口就方便了,在上面给出的上传接口UploadController.upload(MultipartFile file)中,其实隐含了一个操作,就是MultipartFile转File,直接借助MultipartFile.transferTo()就可以写为File类型了,最后我们返回File就可以。 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot使用MultipartFile上传文件以及File与MultipartFile互转 的相关文章

随机推荐

  • node通过node-java库调用java

    node有一个库 node java xff0c 可以通过js的方式调用java语言 xff0c 听起来好像很好玩 xff0c 但是这个玩意要求很复杂 1 本机安装msbuild环境 这个东西简单的安装方式就是npm install g w
  • node-gyp编译c++编写的node扩展

    node有一个模块addon xff0c 翻译过来 xff0c 是插件 xff0c 但是有的地方也叫扩展 xff0c 这部分是用c 43 43 来编写的 xff0c 最后可以通过node gyp来针对各个平台编译适合自己平台的扩展 xff0
  • log4j日志漏洞问题

    去年 xff0c log4j被爆出了一个漏洞 xff0c 说可以通过利用日志格式化中的远程注入控制主机 当时 xff0c 这个漏洞被形容为史诗级漏洞 xff0c 因为这个远程操作可以执行一些操作 xff0c 如果这个操作有恶意 xff0c
  • postgresql数据备份与恢复

    postgresql数据备份与恢复在实际工作中可能会用到 xff0c 这里记录一下自己整理的备份与恢复的过程 xff0c 备份一般使用pg dump来做 xff0c 但是它备份的结果有两种格式 xff0c 默认不加 Fc参数 xff0c 产
  • bat批处理脚本大全

    目录 1 echo 2 注释 3 常见cmd命令 4 参数与变量 5 for循环 6 函数 7 数组 在windows上编程或者制作一些小工具 xff0c 少不了使用批处理脚本 xff0c 而且在各种开发环境搭建中我们经常会看到批处理脚本
  • node日志log4js库使用示例

    在node开发或者electron项目开发中 xff0c 我们可能需要记录日志的功能 xff0c 便于我们出错排查问题 今天介绍node中的日志库log4js log日志记录 xff0c 一般需要配置日志记录的级别 xff0c 日志输出类型
  • Maven项目引用本地jar涉及scope配置

    在项目开发过程中 xff0c 难免遇到需要引用私有jar的情况 xff0c 这时候最好是将该jar推送到私服仓库 xff0c 但是由于种种 现实问题 xff0c 比如权限不够 时间不够等等 于是就可以尝试将jar放入项目中进行集成 xff0
  • postgresql使用pg_basebackup备份与恢复

    postgresql可以使用pg dump pg restore等命令来进行备份与恢复 xff0c 那种情况不用停止pgsql服务 xff0c 只需要执行备份恢复命令即可 今天介绍的这种备份方式 xff0c 类似于文件系统的备份与恢复 xf
  • java中list与数组相互转换

    java中 xff0c list转数组 xff0c 很方便 xff0c list本身自带一个方法toArray xff0c 但是这个方法默认返回的数组类型是Object xff0c 我们可以给toArray 方法传递一个类型参数 xff0c
  • cython混淆加密

    python代码是一种解释型的语言 xff0c 有了代码和环境就可以执行 xff0c 它无需编译 如果需要对代码进行混淆 xff0c 可以借助cython这个库 它的安装很简单 xff0c 直接运行pip install cython就可以
  • python文件夹拷贝思路

    最近在做项目中 xff0c 要使用python xff0c 对文件拷贝有了一些了解 xff0c 这里将自己理解的文件拷贝整理出来 如下所示 xff0c 文件拷贝思路 xff1a 文件拷贝 xff0c 从io上来说就是读文件 xff0c 写文
  • node检测端口是否被占用isPortOccupied.js

    如题所示 xff0c node开发中 xff0c 可能会遇到开启tcp http服务端口被占用的问题 xff0c 解决起来也很简单 xff0c 直接换一个端口就可以了 但是每次启动 xff0c 发现失败 xff0c 然后更改监听端口来测试
  • commons-math3求解线性方程组

    python语言numpy scipy库可以实现矩阵求解线性方程组 xff0c 在java语言中 xff0c commons math3提供了强大的矩阵计算功能 xff0c 同样也可以用来解决线性方程组问题 如下所示 xff0c 线性方程组
  • 2022记忆

    今年开年来就重新找工作 xff0c 因为就在去年大概这个时候 xff0c 公司裁员了 找工作 xff0c 对于我们这种大龄程序员来说是一种挑战 xff0c 很多公司表面说可以聊聊 xff0c 最后谈了之后 xff0c 发现技术也可以 xff
  • java调用js示例

    jdk1 8引入了js引擎功能 xff0c 可以在命令行下运行js交互程序 xff1a 在jdk11之后 xff0c 这个功能又去掉了 如下代码 xff0c 是一个通过js调起计算器的示例 javascript代码 function mai
  • 查询是: LOCK TABLE test.xx_test IN ACCESS SHARE MODE问题解决办法

    如题所示 xff0c 这个问题是我在postgresql中使用pg dump备份多个schema的表时遇到的问题 bin pg dump dbname 61 postgresql dbuser 123456 64 localhost 543
  • 最小二乘法公式推导以及在线性回归中的应用

    机器学习算法中 xff0c 有一个基础的算法 xff0c 线性回归 xff0c 它的目的是求出一条直线 xff0c 满足所有点到这条直线的距离最短 xff0c 也就是这些数据点能够看起来都在这条直线附近 xff0c 最后 xff0c 可以根
  • Java根据经纬度获取地址信息

    使用高德API根据经纬度获取一定范围内的地址信息 PS xff1a 1 高德地图接口Key申请步骤 xff1a https zhuanlan zhihu com p 555130433 2 经纬度在线查询网址 xff1a https map
  • c++改变控制台显示颜色

    这个问题是别人问我怎么把控制台默认黑底白字修改掉的 xff0c 我说我以前做过java语言控制台颜色控制 xff0c c的没试过 后来还是留意了一下 xff0c 发现可以改变控制台显示颜色 如下实例 xff1a include 34 pch
  • springboot使用MultipartFile上传文件以及File与MultipartFile互转

    如下所示的代码 xff0c 是一个在springboot项目中使用MultipartFile进行文件上传的示例 xff1a package com springboot web import org springframework http