Spring中MultipartFile和File转换

6 篇文章 0 订阅
3 篇文章 1 订阅

前言:在SpringBoot项目中经常用到的就是MultipartFile和File转换的问题,一开始我也并不是非常了解,参考了一些资料和ChatGPT的帮助后完成的业务开发,现在有时间就自己总结一下并记录一下简单的用法,可能不是很全

正文:

首先说一下MultipartFile和File是什么:

        MultipartFile是Spring框架提供的一个接口,用于处理HTTP请求中的文件上传。它提供了一些方法来获取文件的相关信息,如文件名、文件大小、文件类型等,并且可以通过流的方式读取文件内容;在使用MultipartFile时,需要导入org.springframework.web.multipart.MultipartFile包路径

        File是Java标准库中的一个类,用于表示操作系统中的文件。它提供了一些方法来操作文件,如创建文件、删除文件、重命名文件等,并且可以通过流的方式读取或写入文件内容;在使用File时,需要导入java.io.File包路径

下面是一个使用MultipartFile接收上传文件并保存到指定路径的快速入门示例代码:

import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

public class FileUploadController {
    public void uploadFile(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 指定保存路径
                String filePath = "D:/upload/";
                // 创建文件对象
                File dest = new File(filePath + fileName);
                // 判断保存路径是否存在,如果不存在则创建
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                // 保存文件
                file.transferTo(dest);
                System.out.println("文件上传成功");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件上传失败");
            }
        }
    }
}

 在上述代码中,首先通过file.getOriginalFilename()方法获取上传文件的文件名,然后指定保存路径,创建一个File对象表示保存的文件路径和文件名。接着判断保存路径是否存在,如果不存在则创建。最后通过file.transferTo(dest)方法将上传的文件保存到指定路径

一、MultipartFile转换为File的三种方式:

1、方式一:transferTo

        这是一种最简单的方法,也是上面快速入门用的方式;transferTo 是MultipartFile自带的方法,它将MultipartFile转换为File,将MultipartFile转换为File格式,然后输出到特定的路径,具体写法如下:

package com.xkcoding.upload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author 听着晴天看星晴
 */
@RestController
@Slf4j
@RequestMapping("/upload")
public class FileController {

    /**
     * 需要保存的本地目录路径
     */
    private static final String UPLOAD_DIR = "D:\\desktop\\ck\\testFile";

    /**
     * 上传文件至本地
     * MediaType.MULTIPART_FORM_DATA_VALUE 用于表示HTTP请求的Content-Type为multipart/form-data
     *
     * @param file 上传文件
     * @return 字符串
     */
    @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "文件为空";
        }

        //确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        //准备要保存的文件
        String fileName = file.getOriginalFilename();
        String localFilePath = UPLOAD_DIR + File.separator + fileName;
        File targetFile = new File(localFilePath);

        try {
            //将上传的文件输出到指定的目标文件中
            file.transferTo(targetFile);
        } catch (IOException e) {
            log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
            return "上传文件异常";
        }

        log.info("【文件上传至本地】绝对路径:{}", localFilePath);
        return "上传成功";
    }
}

2、方式二:使用 FileOutputStream

        这是最常用的一种方法,利用MultipartFile提供的getBytes方法获取上传文件的字节数组,使用FileOutputStream 可以将字节写入文件。具体写法如下:

package com.xkcoding.upload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 听着晴天看星晴
 */
@RestController
@Slf4j
@RequestMapping("/upload")
public class FileController {

    /**
     * 需要保存的本地目录路径
     */
    private static final String UPLOAD_DIR = "D:\\desktop\\ck\\testFile";

    /**
     * 上传文件至本地
     * MediaType.MULTIPART_FORM_DATA_VALUE 用于表示HTTP请求的Content-Type为multipart/form-data
     *
     * @param file 上传文件
     * @return 字符串
     */
    @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        //简单的前置校验
        if (file.isEmpty()) {
            return "文件为空";
        }

        //确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        //准备要保存的文件
        String fileName = file.getOriginalFilename();
        String localFilePath = UPLOAD_DIR + File.separator + fileName;
        File targetFile = new File(localFilePath);

        //获取上传文件的字节数组,使用 FileOutputstream 将字节数组写入到指定的文件
        try(FileOutputStream fileOutputStream = new FileOutputStream(targetFile)) {
            fileOutputStream.write(file.getBytes());
        } catch (IOException e) {
            log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
            return "文件上传失败";
        }

        log.info("【文件上传至本地】绝对路径:{}", localFilePath);
        return "上传成功";
    }
}

3、方式三:使用 Java NIO

        Java NIO 提供了Files.copy()方法,通过获取上传文件的输入流,将输入流的内容通copy方法复制到本地文件路径中,实现了文件的上传功能,具体解释如下:

  • file.getInputStream():获取上传文件的输入流,即文件内容的输入流。
  • localFilePath:表示本地文件路径的Path对象,指定了文件复制的目标位置。
  • StandardCopyOption.REPLACE_EXISTING:表示如果目标文件已经存在,则替换目标文件。这个选项用于确保如果目标文件已经存在,会被新的上传文件覆盖。

其中:

     StandardCopyOption是Java NIO中的一个枚举常量,用于指定在复制文件时如果目标文件已存在时的处理方式

     StandardCopyOption.REPLACE_EXISTING表示如果目标文件已存在,则替换目标文件。如果目标文件不存在,则会创建一个新的文件

                  StandardCopyOption.COPY_ATTRIBUTES: 在文件复制过程中,如果目标文件已存在且不希望被替换,可以使用选项来保留目标文件的属性。

package com.xkcoding.upload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author 听着晴天看星晴
 */
@RestController
@Slf4j
@RequestMapping("/upload")
public class FileController {

    /**
     * 需要保存的本地目录路径
     */
    private static final String UPLOAD_DIR = "D:\\desktop\\ck\\testFile";

    /**
     * 上传文件至本地
     * MediaType.MULTIPART_FORM_DATA_VALUE 用于表示HTTP请求的Content-Type为multipart/form-data
     *
     * @param file 上传文件
     * @return 字符串
     */
    @PostMapping(value = "/local", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        //简单的前置校验
        if (file.isEmpty()) {
            return "文件为空";
        }

        //确保上传目录存在
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        //定义保存文件的路径
        //创建一个Path对象,表示上传目录的路径
        Path uploadPath = Paths.get(UPLOAD_DIR);
        //获取上传文件的原始文件名
        String fileName = file.getOriginalFilename();
        //使用上传目录路径和文件名创建一个新的Path对象,表示上传文件的本地路径
        Path localFilePath = uploadPath.resolve(fileName);

        //将上传文件的内容复制到本地文件路径中
        try (InputStream inputStream = file.getInputStream()) {
            //file.getInputStream():获取上传文件的输入流,即文件内容的输入流。
            //localFilePath:表示本地文件路径的Path对象,指定了文件复制的目标位置。
            //StandardCopyOption.REPLACE_EXISTING:表示如果目标文件已经存在,则替换目标文件。这个选项用于确保如果目标文件已经存在,会被新的上传文件覆盖。
            Files.copy(inputStream, localFilePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            log.error("【文件上传至本地】失败,绝对路径:{}", localFilePath);
            return "文件上传失败";
        }

        log.info("【文件上传至本地】绝对路径:{}", localFilePath);
        return "上传成功";
    }
}

二、File转换为MultipartFile

        从File转换为MultipartFile 通常在测试或模拟场景中使用,生产环境一般不这么用,这里只介绍一种最常用的方法。

        使用 MockMultipartFile:通过获得File文件的名称、mime类型以及内容将其转换为MultipartFile格式。具体写法如下

在转换之前先确保引入了spring-test 依赖(以Maven举例)

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>version</version>
    <scope>test</scope>
</dependency>
package com.xkcoding.upload.controller;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author 听着晴天看星晴
 */
public class MultiToFileUtil {
    public static MultipartFile convertMockMultipartFile(String filePath) throws IOException {
        //根据提供的文件路径创建对象
        Path path = Paths.get( filePath );

        // 获取文件的名字
        String name = path.getFileName().toString();

        //使用 Java NIO 的 Files 类探测文件的 MIME 类型
        String contentType = Files.probeContentType(path);

        //读取文件内容为字节数组
        byte[] content = Files.readAllBytes(path);

        //需要引入spring-test依赖
        return new MockMultipartFile(name, name, contentType, content);
    }
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值