其實springboot中上傳文件和在springmvc中上傳的方式基本一致,沒多大區別,當然在springboot沒多少配置,更加簡單一點。
一、在application.properties中我們只需寫上如下兩行配置。
(其實不寫這個也是可以的,只要你的單個文件小於1M)
<code># 上傳文件總的最大值
spring.servlet.multipart.max-request-size=10MB
# 單個文件的最大值(注:springboot默認的文件大小限制為1M)
spring.servlet.multipart.max-file-size=5MB
/<code>
二、完整例子(這裡我們以上傳圖片演示)
我們先在static目錄下創建一個upload目錄
unloadController.java
<code>package com.rong.upload.controller;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
@Controller
public class UploadController {
//用於轉到upload.html
@RequestMapping("/totest")
public String toUpload(){
return "upload";
}
//用於接收文件
@RequestMapping("/upload")
public ModelAndView upload(MultipartFile photo) throws IOException {
ModelAndView mv = new ModelAndView();
//判斷用戶是否上傳了文件
if(!photo.isEmpty()){
//文件上傳的地址
String path = ResourceUtils.getURL("classpath:").getPath()+"static/upload";
String realPath = path.replace('/', '\\\\').substring(1,path.length());
//用於查看路徑是否正確
System.out.println(realPath);
//獲取文件的名稱
final String fileName = photo.getOriginalFilename();
//限制文件上傳的類型
String contentType = photo.getContentType();
if("image/jpeg".equals(contentType) || "image/jpg".equals(contentType) ){
File file = new File(realPath,fileName);
//完成文件的上傳
photo.transferTo(file);
System.out.println("圖片上傳成功!");
String path01 = "../upload/"+fileName;
mv.addObject("path" ,path01);
mv.setViewName("lookphoto");
return mv;
} else {
System.out.println("上傳失敗!");
mv.setViewName("upload");
return mv;
}
} else {
System.out.println("上傳失敗!");
mv.setViewName("upload");
return mv;
}
}
}
/<code>
unload.html(用於上傳文件)
<code>
<title>upload/<title>
/<code>
lookphoto.html(用於查看上傳成功的圖片)
<code>
<title>lookphoto/<title>
/<code>
三、演示結果
(1)輸入localhost:8080/totest選擇文件上傳
(2)上傳文件成功顯示該圖片
(3)查看target下是否有圖片
四、上傳文件需要注意的地方
- 1.我們需要轉發到html頁面,所以別忘了添加thymeleaf模板引擎。
- 2.如果上面上傳的文件路徑存在問題,可以直接手寫一個,例如D:\\IdeaProjects\\learnspringboot\\\\upload\\target\\classes\\static\\\\upload(注意了\\需要用\\\\轉義)
- 3.查看上傳成功的圖片要到target目錄下查看。
鏈接:https://blog.csdn.net/chaseqrr/article/details/105159392?depth_1-utm_source=distribute.pc_category.none-task&request_id=&utm_source=distribute.pc_category.none-task
閱讀更多 旅途中的saber 的文章