SpringBoot文件上傳
阿新 • • 發佈:2018-02-23
view spring fileutil request stp Enctype amp quest span
先建工程
只勾選web和freemarker模板
最後
先看一下最終目錄結構
先修改pom文件,加入common-io依賴
然後修改Application.yml文件
spring: freemarker: templateLoaderPath: classpath:/templates/ content-type: text/html charset: UTF-8 suffix: .ftl
然後新建一個controller
package com.example.demo.controller; import org.apache.commons.io.FileUtils;import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; importjavax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; @RestController public class FileController { @RequestMapping("/index") public ModelAndView index(){ ModelAndView mv = new ModelAndView("index"); return mv; } @RequestMapping("/upload")public String upload(HttpServletRequest request, @RequestParam("myFile")MultipartFile file) throws IOException { if (file.isEmpty()) return "No File"; String name = file.getOriginalFilename(); System.out.println("FileName:" + name); String fileType = name.substring(name.lastIndexOf(".")); System.out.println("FileType:" + fileType); String size = FileUtils.byteCountToDisplaySize(file.getSize()); System.out.println("FileSize:" + size); String path = request.getSession().getServletContext().getRealPath("/static/img/"); File desFile = new File(path+name); FileUtils.copyInputStreamToFile(file.getInputStream(), desFile); String info = desFile.getAbsolutePath(); return info; } }
最後新建一個頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$Title$</title> </head> <body> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="myFile"> <input type="submit" value="Upload"> </form> </body> </html>
PS:這裏沒有啟動類的事,因為啟動類的上層沒有任何代碼(官方建議啟動類放在根目錄)
啟動應用
..
..返回結果
..查看控制臺
..找到本地文件
..看看可不可以訪問
SpringBoot文件上傳