springboot学习[版本2.6.2]文件上传day4-2

349 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

文件上传

MultipartFile类

在多部分请求中接收的上载文件的表示形式。 文件内容要么存储在内存中,要么临时存储在磁盘上。在这两种情况下,如果需要,用户负责将文件内容复制到会话级别或持久存储。临时存储将在请求处理结束时清除。

源码

/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.multipart;

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

import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import org.springframework.util.FileCopyUtils;

/**
 * A representation of an uploaded file received in a multipart request.
 *
 * <p>The file contents are either stored in memory or temporarily on disk.
 * In either case, the user is responsible for copying file contents to a
 * session-level or persistent store as and if desired. The temporary storage
 * will be cleared at the end of request processing.
 *
 * @author Juergen Hoeller
 * @author Trevor D. Cook
 * @since 29.09.2003
 * @see org.springframework.web.multipart.MultipartHttpServletRequest
 * @see org.springframework.web.multipart.MultipartResolver
 */
public interface MultipartFile extends InputStreamSource {

	/**
	 * Return the name of the parameter in the multipart form.
	 * @return the name of the parameter (never {@code null} or empty)
	 */
	String getName();

	/**
	 * Return the original filename in the client's filesystem.
	 * <p>This may contain path information depending on the browser used,
	 * but it typically will not with any other than Opera.
	 * <p><strong>Note:</strong> Please keep in mind this filename is supplied
	 * by the client and should not be used blindly. In addition to not using
	 * the directory portion, the file name could also contain characters such
	 * as ".." and others that can be used maliciously. It is recommended to not
	 * use this filename directly. Preferably generate a unique one and save
	 * this one one somewhere for reference, if necessary.
	 * @return the original filename, or the empty String if no file has been chosen
	 * in the multipart form, or {@code null} if not defined or not available
	 * @see org.apache.commons.fileupload.FileItem#getName()
	 * @see org.springframework.web.multipart.commons.CommonsMultipartFile#setPreserveFilename
	 * @see <a href="https://tools.ietf.org/html/rfc7578#section-4.2">RFC 7578, Section 4.2</a>
	 * @see <a href="https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload">Unrestricted File Upload</a>
	 */
	@Nullable
	String getOriginalFilename();

	/**
	 * Return the content type of the file.
	 * @return the content type, or {@code null} if not defined
	 * (or no file has been chosen in the multipart form)
	 */
	@Nullable
	String getContentType();

	/**
	 * Return whether the uploaded file is empty, that is, either no file has
	 * been chosen in the multipart form or the chosen file has no content.
	 */
	boolean isEmpty();

	/**
	 * Return the size of the file in bytes.
	 * @return the size of the file, or 0 if empty
	 */
	long getSize();

	/**
	 * Return the contents of the file as an array of bytes.
	 * @return the contents of the file as bytes, or an empty byte array if empty
	 * @throws IOException in case of access errors (if the temporary store fails)
	 */
	byte[] getBytes() throws IOException;

	/**
	 * Return an InputStream to read the contents of the file from.
	 * <p>The user is responsible for closing the returned stream.
	 * @return the contents of the file as stream, or an empty stream if empty
	 * @throws IOException in case of access errors (if the temporary store fails)
	 */
	@Override
	InputStream getInputStream() throws IOException;

	/**
	 * Return a Resource representation of this MultipartFile. This can be used
	 * as input to the {@code RestTemplate} or the {@code WebClient} to expose
	 * content length and the filename along with the InputStream.
	 * @return this MultipartFile adapted to the Resource contract
	 * @since 5.1
	 */
	default Resource getResource() {
		return new MultipartFileResource(this);
	}

	/**
	 * Transfer the received file to the given destination file.
	 * <p>This may either move the file in the filesystem, copy the file in the
	 * filesystem, or save memory-held contents to the destination file. If the
	 * destination file already exists, it will be deleted first.
	 * <p>If the target file has been moved in the filesystem, this operation
	 * cannot be invoked again afterwards. Therefore, call this method just once
	 * in order to work with any storage mechanism.
	 * <p><b>NOTE:</b> Depending on the underlying provider, temporary storage
	 * may be container-dependent, including the base directory for relative
	 * destinations specified here (e.g. with Servlet 3.0 multipart handling).
	 * For absolute destinations, the target file may get renamed/moved from its
	 * temporary location or newly copied, even if a temporary copy already exists.
	 * @param dest the destination file (typically absolute)
	 * @throws IOException in case of reading or writing errors
	 * @throws IllegalStateException if the file has already been moved
	 * in the filesystem and is not available anymore for another transfer
	 * @see org.apache.commons.fileupload.FileItem#write(File)
	 * @see javax.servlet.http.Part#write(String)
	 */
	void transferTo(File dest) throws IOException, IllegalStateException;

	/**
	 * Transfer the received file to the given destination file.
	 * <p>The default implementation simply copies the file input stream.
	 * @since 5.1
	 * @see #getInputStream()
	 * @see #transferTo(File)
 	 */
	default void transferTo(Path dest) throws IOException, IllegalStateException {
		FileCopyUtils.copy(getInputStream(), Files.newOutputStream(dest));
	}

}

方法

getName()

String getName();

用途:

返回参数的名称 注意这里不是返回文件的名称而是你定义的那个接收文件的变量的名称 在这里插入图片描述 在这里插入图片描述 最后打印出来的是headImg就是这个变量名

getOriginalFilename()

String getOriginalFilename();

用途:

返回原本的文件全称(文件名+后缀名) 当我们上传一个叫headphoto.png的图片,这个方法就会返回文件的全称headphoto.png,后缀名也会返回

getContentType()

String getContentType();

用途:

返回文件类型

isEmpty()

boolean isEmpty();

用途:

判断是否为空,即是否上传或上传是否成功

getSize()

long getSize();

用途:

获取上传文件的字节数

getBytes()

byte[] getBytes() throws IOException;

用途:

以字节数组的形式返回文件的内容

getInputStream()

InputStream getInputStream() throws IOException;

用途:

getResource()

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

用途:

返回InputStream以从中读取文件内容。 用户负责关闭返回的流。

transferTo(File dest)

void transferTo(File dest) throws IOException, IllegalStateException;

用途:

将文件写入(保存到)指定位置

String originalFilename = headImg.getOriginalFilename();
headImg.transferTo(new File("D:\\uploaddata\\"+originalFilename));

@RequestPart和@RequestParam

两者都可以使用来表单提交请求,@RequestPart用于更加复杂的场合而@RequestParam用于比较简单的。 他们都可以和MultipartFile一起使用

实例

FromUploadController

package com.example.day3.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 文件上传
 */
@Controller
@Slf4j
public class FromUploadController {

    @GetMapping("/uploadForm")
    public String uploadForm(){
        return "form/uploadForm";
    }

    /**
     * MultipartFile自动封装上传的文件
     * @param username
     * @param headImg
     * @param photos
     * @return
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {
    log.info("上传的信息:username={},headerImg.size={},photos.length={}",
            username,headImg.getSize(),photos.length);

    if (!headImg.isEmpty()){
        //保存到文件服务器(本地)
        String originalFilename = headImg.getOriginalFilename();
        headImg.transferTo(new File("D:\\uploaddata\\"+originalFilename));
//        System.out.println(headImg.getOriginalFilename());
//        System.out.println(headImg.getContentType());
//        System.out.println(headImg.getSize());

        if (photos.length>0){
            for (MultipartFile photo:photos){
                if (!photo.isEmpty()){
                    String photoFilename = photo.getOriginalFilename();
                    photo.transferTo(new File("D:\\uploaddata\\"+photoFilename));
                }
            }
        }

    }
        return "main";
    }
}

uploadForm.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #headImg {
            height: 300px;
            width: 250px;
            background-color: silver;
        }
    </style>
</head>
<body>
<h2>文件上传</h2>
<!--  表单上传的固定写法-->
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
    <!--        多文件上传实用multiple属性-->
    username:<input type="text" name="username"><br>
    <input type="file" name="headerImg" id="headImg"><br>
    <input type="file" name="photos" multiple><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

表单上传的固定写法

enctype="multipart/form-data"

<!--  表单上传的固定写法-->
<form role="form" th:action="@{/upload}" method="post" enctype="multipart/form-data">
</form>

application.yaml配置

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB

展示

在这里插入图片描述 在这里插入图片描述