下面先来演示上传一张图片的操作,先创建一个新的Spring Boot的项目demo02,然后我们在resources目录下面的static目录下创建一个带表单的index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="headerImg"><br> <input type="submit" value="提交"> </form> </body> </html>
我们还要再创建一个controller进行测试:
package com.example.demo02.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; 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.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @Controller public class UploadController { private static final Logger log = LoggerFactory.getLogger(UploadController.class); /** * MultipartFile 自动封装上传过来的文件 * @param headerImg * @return */ @PostMapping("/upload") @ResponseBody public String upload(@RequestPart("headerImg") MultipartFile headerImg) throws IOException { log.info("上传的信息:headerImg={}",headerImg.getSize()); if(!headerImg.isEmpty()){ //保存到文件服务器 String originalFilename = headerImg.getOriginalFilename(); headerImg.transferTo(new File("D:\\cache\\"+originalFilename)); } return "上传成功!"; } }
运行项目上传图片前要先保证存放的文件夹得存在,不然会报错。
下面来演示上传多张图片得的操作,我们只要接收一个MultipartFile数组就好了。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="photos" multiple="multiple"><br> <input type="submit" value="提交"> </form> </body> </html>
/** * MultipartFile 自动封装上传过来的文件 * @param photos * @return */ @PostMapping("/upload") @ResponseBody public String upload(@RequestPart("photos") MultipartFile[] photos) throws IOException { if(photos.length > 0){ for (MultipartFile photo : photos) { if(!photo.isEmpty()){ String originalFilename = photo.getOriginalFilename(); photo.transferTo(new File("D:\\cache\\"+originalFilename)); } } } return "上传成功!"; }