1 packagecom.atguigu.controller;2
3 importorg.springframework.stereotype.Controller;4 importorg.springframework.ui.Model;5 importorg.springframework.web.bind.annotation.RequestMapping;6 importorg.springframework.web.bind.annotation.RequestParam;7 importorg.springframework.web.multipart.MultipartFile;8
9 importjava.io.File;10 importjava.io.IOException;11
12 /**
13 * @Title: FileUploadController14 * @Description:15 * @Author:16 * @Version: 1.017 * @create 2020/6/22 10:2818 */
19 @Controller20 public classFileUploadController {21
22 /**
23 * @Description: 单文件上传24 * @Param: [username, file, model]25 * @Return: java.lang.String26 * @Author:27 * @Date: 2020/6/22 10:4928 */
29 /*@RequestMapping("/upload")30 public String upload(@RequestParam(value = "username", required = false) String username,31 @RequestParam("headerimg") MultipartFile file,32 Model model) {33 System.out.println("上传的文件信息");34 System.out.println("文件项的name" + file.getName());//headerimg35 System.out.println("文件的名字" + file.getOriginalFilename());36
37 //文件保存38 try {39 file.transferTo(new File("E:\\upload\\" + file.getOriginalFilename()));40 model.addAttribute("msg", "文件上传成功");41 } catch (IOException e) {42 model.addAttribute("msg", "文件上传失败" + e.getMessage());43 }44 return "forward:/index.jsp";45 }*/
46
47 /**
48 * @Description: 多文件上传49 * @Param: [username, file, model]50 * @Return: java.lang.String51 * @Author:52 * @Date: 2020/6/22 10:4953 */
54 @RequestMapping("/upload")55 public String upload(@RequestParam(value = "username", required = false) String username,56 @RequestParam("headerimg") MultipartFile[] file,57 Model model) {58
59 for(MultipartFile multipartFile : file) {60 if(!multipartFile.isEmpty()){61 System.out.println("上传的文件信息");62 System.out.println("文件项的name" + multipartFile.getName());//headerimg
63 System.out.println("文件的名字" +multipartFile.getOriginalFilename());64 try{65 multipartFile.transferTo(new File("E:\\upload\\" +multipartFile.getOriginalFilename()));66 model.addAttribute("msg", "文件上传成功");67 } catch(IOException e) {68 model.addAttribute("msg", "文件上传失败" +e.getMessage());69 }70 }71 }72 return "forward:/index.jsp";73 }74 }