SpringBoot文件上传
先建工程
只勾选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; import javax.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:这里没有启动类的事,因为启动类的上层没有任何代码(官方建议启动类放在根目录)
启动应用
..
..返回结果
..查看控制台
..找到本地文件
..看看可不可以访问
小LUA
面对敌人的严刑逼供,我一个字也没说,而是一五一十写了下来。