SpringBoot文件上傳

https://blog.csdn.net/cx243698/article/details/80234444html

咱們在工做中常常會遇到文件上傳的需求,本文使用SpringBoot簡單實現文件上傳。前端

首先Pom.xml

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- thmleaf模板依賴. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>git

編寫Controller層

@Controller
public class FileUploadController {

private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

/**
* 跳轉到單個文件上傳
*
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public ModelAndView upload() {
return new ModelAndView("/fileUpload");
}

/**
* 跳轉到多個文件上傳
*
* @return
*/
@RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
public ModelAndView batchUpload() {
return new ModelAndView("/multiFileUpload");
}

/**
* 文件上傳具體實現方法(單文件上傳)
*
* @param file
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件爲空";
}
// 獲取文件名
String fileName = file.getOriginalFilename();
logger.info("上傳的文件名爲:" + fileName);
// 獲取文件的後綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("文件的後綴名爲:" + suffixName);

// 設置文件存儲路徑
String filePath = "E://xuchen//";
String path = filePath + fileName + suffixName;

File dest = new File(path);
// 檢測是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夾
}
file.transferTo(dest);
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}

/**
* 多文件上傳
*
* @param request
* @return
*/
@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
@ResponseBody
public String batchUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file;
BufferedOutputStream stream;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
stream = null;
return "文件上傳失敗 " + i + " => " + e.getMessage();
}
} else {
return "文件上傳失敗 " + i + "緣由:上傳文件爲空!";
}
}
return "文件上傳成功";
}
}web

文件上傳相關配置


@Configuration
public class FileUploadConfiguration {

@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 設置文件大小限制 ,超出設置頁面會拋出異常信息,
// 這樣在文件上傳的地方就須要進行異常信息的處理了;
factory.setMaxFileSize("2MB");
/// 設置總上傳數據總大小
factory.setMaxRequestSize("5MB");
return factory.createMultipartConfig();
}
}spring

前端頁面(單個上傳)


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>單個文件上傳</title>
</head>
<body>
<h2>文件上傳示例</h2>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/upload">
<p>
文件:<input type="file" name="file"/>
</p>
<p>
<input type="submit" value="上傳"/>
</p>
</form>
</body>
</html>app

測試結果

 

Demo源碼下載地址:https://gitee.com/inchlifc/SpringBootTest.gitspring-boot

相關文章
相關標籤/搜索