package com.java.controller; import java.io.File; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; /*** * 文件上传控制类 * @author swinglife * */ @Controller @RequestMapping("/files") public class FileUploadController { //通过Spring的autowired注解获取spring默认配置的request @Autowired private HttpServletRequest request; @RequestMapping("filesUpload") public void filesUpload(@RequestParam("files") MultipartFile[] files) { //判断file数组不能为空并且长度大于0 if(files!=null&&files.length>0){ //循环获取file数组中得文件 for(int i = 0;i<files.length;i++){ MultipartFile file = files[i]; //保存文件 saveFile(file); } } // 重定向 /*return "filesUpload";*/ } /*** * 保存文件 * @param file * @return */ private boolean saveFile(MultipartFile file) { // 判断文件是否为空 if (!file.isEmpty()) { try { // 文件保存路径 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename(); // 转存文件 file.transferTo(new File(filePath)); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } /*** * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile * * @param file * @return */ @RequestMapping("fileUpload") public String fileUpload(@RequestParam("file") MultipartFile file) { // 判断文件是否为空 if (!file.isEmpty()) { try { // 文件保存路径 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/" + file.getOriginalFilename(); // 转存文件 file.transferTo(new File(filePath)); } catch (Exception e) { e.printStackTrace(); } } // 重定向 return "redirect:/list.html"; } /*** * 读取上传文件中得所有文件并返回 * * @return */ @RequestMapping("list") public ModelAndView list() { String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; ModelAndView mav = new ModelAndView("list"); File uploadDest = new File(filePath); String[] fileNames = uploadDest.list(); for (int i = 0; i < fileNames.length; i++) { System.out.println(fileNames[i]); } return mav; } }

lcqlcl LV11
2023年8月29日
ewan007 LV30
2022年6月24日
唐T袋D皓H LV4
2022年4月1日
lcy123ww LV5
2022年3月31日
Bettytian LV9
2021年4月14日
wxlssss LV7
2021年4月11日
写梦追逐 LV8
2021年3月28日
qqwjk123 LV2
2021年1月8日
qianyexingren LV10
2021年1月8日
qq278246140 LV12
2020年10月18日

ChanLain LV2
2024年6月8日
uni-code_0123 LV1
2023年11月29日
lcqlcl LV11
2023年8月29日
asdfg01234 LV10
2023年7月31日
25702204 LV1
2023年5月24日
李亮 LV19
2023年3月5日
qwer123978ca LV1
2022年12月19日
wyxjusj LV1
2022年12月5日
getset LV8
2022年12月3日
zxc131313 LV12
2022年11月28日