1、簡介
html
Spring Boot默認使用springMVC包裝好的解析器進行上傳java
2、代碼實現web
2.一、from表單
spring
<form method="POST" enctype="multipart/form-data" action="/file/upload"> 文件:<input type="file" name="roncooFile" /> <input type="submit" value="上傳" /> </form>
2.二、controller
app
package com.example.demo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; /** * 文件上傳 * @Author: 我愛大金子 * @Description: 文件上傳 * @Date: Created in 11:08 2017/6/18 */ @Controller @RequestMapping(value = "/file") public class FileController { private static final Logger logger = LoggerFactory.getLogger(FileController.class); @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("roncooFile") MultipartFile file) { if (file.isEmpty()) { return "文件爲空"; } // 獲取文件名 String fileName = file.getOriginalFilename(); logger.info("上傳的文件名爲:" + fileName); // 獲取文件的後綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上傳的後綴名爲:" + suffixName); // 文件上傳路徑 String filePath = "G:/workspace/file_space/img/"; // 解決中文問題,liunx 下中文路徑,圖片顯示問題 //fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; } }
2.三、application.propertiesdom
#默認支持文件上傳 spring.http.multipart.enabled=true #支持文件寫入磁盤. spring.http.multipart.file-size-threshold=0 #上傳文件的臨時目錄 spring.http.multipart.location=G:/workspace/file_space/temp # 最大支持文件大小 spring.http.multipart.max-file-size=1Mb #最大支持請求大小 spring.http.multipart.max-request-size=10Mb
3、測試ide