将文件上传到服务器上:
上传html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form name="Form2" action="http://localhost:8080/test9" method="post" enctype="multipart/form-data"> <h1>spring mvc shangchuan</h1> <input type="file" name="file"> <input type="submit" value="upload"/> </form> </body> </html>
控制器:
package com.awaimai.web; import org.hibernate.validator.constraints.Range; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @Controller @Validated public class kzq { /* *采用spring提供的上传文件的方法 */ @RequestMapping("/test9") @ResponseBody public String springUpload(@RequestParam("file")MultipartFile scfile) throws IllegalStateException, IOException { scfile.transferTo(Paths.get("C:\\Users\\del\\IdeaProjects\\helloweb\\src\\main\\resources\\uploadFiles\\abc.xlsx")); return "/success"; } }
web访问:
上传成功:
重点:
ransferTo方法中传递的file如果是路径的话,那么它会将最后一层路径当做文件名,没有后缀的那种。
此时重命名这个文件,更改成和上传文件一致的后缀那么就可以打开了。