package com.smartmap.sample.ch1.controller.view;import java.io.File;import java.io.IOException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.env.Environment;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.smartmap.sample.ch1.service.UserService;@Controller@RequestMapping("/system/page/user")public class UserViewController { @Autowired UserService userService; @Autowired private Environment environment; @GetMapping("/list.html") public String userList(Model model) { String osName = System.getProperty("os.name"); model.addAttribute("name", "hello world"); model.addAttribute("host", osName); return "user/list"; } @GetMapping("/userdetail.html") public String userdetail(String id) { return "admin/userInfo.jsp"; } /** * 文件上传 * * curl -XPOST 'http://127.0.0.1:8080/system/page/user/upload.html' -F * "multipartFile=@/D/Project/JavaWeb/SpringBoot/01HelloSpringBoot/readme.txt" * -F "name=123456789" * * curl -XPOST 'http://127.0.0.1:8080/system/page/user/upload.html' -F * "multipartFile=@readme.txt;type=application/octet-stream" -F "name=123456789" * * @param name * @param multipartFile * @return * @throws IllegalStateException * @throws IOException */ @PostMapping("/upload.html") @ResponseBody public String handleFormUpload(String name, MultipartFile multipartFile) throws IllegalStateException, IOException { String resultMessage = "{success: false, message: 'upload fail'}"; System.out.println(multipartFile); if (!multipartFile.isEmpty()) { String fileName = multipartFile.getOriginalFilename(); // InputStream is = multipartFile.getInputStream(); String fileSavePath = environment.getProperty("file.upload.path", ""); if (!fileSavePath.equals("")) { File file = new File(fileSavePath + java.io.File.separator + fileName); if (file.exists()) { file.delete(); } multipartFile.transferTo(file); resultMessage = "{success: true, message: 'upload success'}"; } } return resultMessage; }}
application.properties
file.upload.path=D:/Project/JavaWeb/SpringBoot/01HelloSpringBoot/fileUpLoadspring.servlet.multipart.enabled=truespring.servlet.multipart.file-size-threshold=0spring.servlet.multipart.location=D:/Project/JavaWeb/SpringBoot/01HelloSpringBoot/tempspring.servlet.multipart.max-file-size=10MBspring.servlet.multipart.max-request-size=10MBspring.servlet.multipart.resolve-lazily=false