MultipartFile实现文件上传与下载

MultipartFile介绍
  在Java中实现文件上传、下载操作一直是一种令人烦躁的工作。但是随着Spring框架的发展,使用Spring框架中的MultipartFile来处理文件就是一件比较简单的事情。
  MultipartFile类是org.springframework.web.multipart包下面的一个类,如果想使用MultipartFile类来进行文件操作,那么一定要引入Spring框架。MultipartFile主要是用表单的形式进行文件上传,在接收到文件时,可以获取文件的相关属性,比如文件名、文件大小、文件类型等等。

Controller类

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * 测试文件下载、上传、解析
 * @auther Yoko
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileTestController {
    /**
     * @description 文件上传,入参可以根据具体业务进行添加
     */
    @RequestMapping(value = "/upLoadFile", method = RequestMethod.POST)
    public void upLoadFile(@RequestBody MultipartFile file) {
        log.info("测试MultipartFile实现文件上传");
        // 获取文件的完整名称,文件名+后缀名
        System.out.println(file.getOriginalFilename());
        // 文件传参的参数名称
        System.out.println(file.getName());
        // 文件大小,单位:字节
        System.out.println(file.getSize());
        // 获取文件类型,并非文件后缀名
        System.out.println(file.getContentType());
        try {
            // MultipartFile 转 File
            File resultFile = FileUtil.MultipartFileToFile(file);
            System.out.println(resultFile.getName());

            // File 转 MultipartFile
            MultipartFile resultMultipartFile = FileUtil.FileToMultipartFile(resultFile);
            System.out.println(resultMultipartFile.getSize());

        } catch (IOException e) {
            log.info("文件转换异常");
        }

    }
    /**
     * @description 文件下载,入参可以根据具体业务进行添加,比如下载具体编码的文件
     */
    public void downLoadFile() throws IOException {
        log.info("测试文件下载至浏览器默认地址");
        File file = new File("测试文件.xlsx");
        FileSystemResource fileSource = new FileSystemResource(file);
        FileUtil.downLoadFile(fileSource.getInputStream(), URLEncoder.encode(Objects.requireNonNull(fileSource.getFilename()), "UTF-8"));
    }
}

FileUtil类

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.Objects;

/**
 * @auther Yoko
 */
public class FileUtil {

    /**
     * MultipartFile类型转File类型,文件名同被转换文件名称一致,如有需要可以拓展方法。
     */
    public static File MultipartFileToFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile.isEmpty()) {
            return null;
        }
        // 获取InoutString
        InputStream inputStream = multipartFile.getInputStream();
        // 创建文件
        File toFile = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        // 写入文件
        OutputStream outputStream = new FileOutputStream(toFile);
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        return toFile;
    }

    /**
     * File类型转MultipartFile类型,文件名同被转换文件名称一致,如有需要可以拓展方法。
     */
    public static MultipartFile FileToMultipartFile(File file) throws IOException {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        FileInputStream fis = new FileInputStream(file);
        OutputStream os = item.getOutputStream();
        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        fis.close();
        return new CommonsMultipartFile(item);

    }

    /**
     * 将File文件转化为Base64字节码
     */
    public static String encodeBase64File(File file) throws IOException {
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        int read = inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }

    /**
     * 将base64字符保存文本文件
     */
    public static void decoderBase64File(String base64Code, String targetPath) throws IOException {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    /**
     * 下载文件至浏览器默认位置
     */
    public static ResponseEntity<InputStreamResource> downLoadFile(InputStream in, String fileName) throws IOException {
        byte[] testBytes = new byte[in.available()];
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(testBytes.length)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(in));
    }
}
posted @ 2021-07-26 10:10  梨猫南北  阅读(15536)  评论(1编辑  收藏  举报