springboot學習[版本2.6.2]檔案上傳day4-2

2022-01-11 23:00:02

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

展示

在這裡插入圖片描述
在這裡插入圖片描述