Spring Boot学習ノート4——ファイルアップロード
2129 ワード
springbootのファイルアップロードは基本的なファイルアップロード操作と同じで、非常に多くの操作を簡略化しました.使用するのはとても簡単です.
1.まずファイルをアップロードしたフォームを書いてください.ここのenctypeはmultiipad/form-dataに変えなければなりません.
1.まずファイルをアップロードしたフォームを書いてください.ここのenctypeはmultiipad/form-dataに変えなければなりません.
Insert title here
2.バックグラウンドでファイルを処理して、Dディスクの下でuploadedフォルダを作成することを覚えています.package com.xx.controller;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@RequestMapping("/file.html")
public String fileHTML() {
return "file";
}
//
@Value("${file.path}")
private String path;
// ,springboot ,
@PostMapping("/file")
public void file(MultipartFile file) throws FileNotFoundException, IOException {
// , ,
//String path = "D:\\uploaded\\";
// , ,
//String fileName = file.getOriginalFilename();
//
String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
// spring
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(path+fileName+suffix));
}
}
3.プロファイルを変更します.これはspringbootを変更せずにデフォルトのファイルアップロードプロファイルを提供できます.#
spring.servlet.multipart.max-file-size=10MB
#
spring.servlet.multipart.max-request-size=50MB
#
file.path=d:/uploaded/