SpringMVC 使用 MultipartFile 实现文件上传
该代码实现了文件上传和文本字段同时传递到后台进行处理的功能。
直接贴代码,中间涉及到的实体类就不贴了,和功能没啥关系的。
Controller
1 /** 2 * 添加活动 3 * 4 * @param req 5 * @param file1 6 * @param file2 7 * @return 8 */ 9 @RequestMapping(value = "/addActivity", method = RequestMethod.POST) 10 public JSONObject addActivity(HttpServletRequest req, @RequestParam(value = "file1") MultipartFile file1, 11 @RequestParam(value = "file2") MultipartFile file2) { 12 logger.info("enter into method addActivity"); 13 StatusCode statusCode = activityService.addActivity(req, file1, file2); 14 return new ResultBuilder<>(statusCode).toJSONObject(); 15 }
Service
1 /** 2 * 添加活动 3 * @param req 4 * @param file1 5 * @param file2 6 * @return 7 */ 8 public StatusCode addActivity(HttpServletRequest req, MultipartFile file1, MultipartFile file2) { 9 try { 10 //从request中获取上传的文件 11 /*if(file1 == null){ 12 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)req; 13 file1 = multipartRequest.getFile("file1"); 14 } 15 if(file2 == null){ 16 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)req; 17 file2 = multipartRequest.getFile("file2"); 18 }*/ 19 20 if (file1 == null || file2 == null) { 21 logger.info("the file is null"); 22 return StatusCode.FILE_IS_NULL; 23 } 24 25 String filepath1 = uploadFile(file1); 26 String filepath2 = uploadFile(file2); 27 if (filepath1 == null || filepath2 == null) { 28 logger.info("the file upload fail"); 29 return StatusCode.FILE_UPLOAD_FAIL; 30 } 31 32 String activityname = req.getParameter("activityname");//活动名称 33 String winrate = req.getParameter("winrate");//中奖率 34 String expectedwinners = req.getParameter("expectedwinners");//预期中奖人数 35 String daysnum = req.getParameter("daysnum");//每天首次访问小程序可获得的抽奖次数 36 String firstnum = req.getParameter("firstnum");//首次关注公众号可获得的抽奖次数 37 String sharelimitnum = req.getParameter("sharelimitnum");//每日分享最多可获得的抽奖次数 38 String friendclicknum = req.getParameter("friendclicknum");//每日好友点击最多可获得的抽奖次数 39 String ruledesc = req.getParameter("ruledesc");//规则描述 40 String starttime = req.getParameter("starttime");//开始时间 41 String endtime = req.getParameter("endtime");//结束时间 42 String prizename = req.getParameter("prizename");//奖品名称 43 String prizeprice = req.getParameter("prizeprice");//奖品价格 44 String cardid = req.getParameter("cardid");//卡片ID 45 46 if (StringUtils.isNullOrEmpty(activityname) || StringUtils.isNullOrEmpty(expectedwinners) || StringUtils.isNullOrEmpty(daysnum) 47 || StringUtils.isNullOrEmpty(firstnum) || StringUtils.isNullOrEmpty(sharelimitnum) || StringUtils.isNullOrEmpty(friendclicknum) 48 || StringUtils.isNullOrEmpty(ruledesc) || StringUtils.isNullOrEmpty(starttime) || StringUtils.isNullOrEmpty(endtime) 49 || StringUtils.isNullOrEmpty(prizename) || StringUtils.isNullOrEmpty(prizeprice) || StringUtils.isNullOrEmpty(cardid) 50 || StringUtils.isNullOrEmpty(winrate)) { 51 logger.info("the paramter is null or empty"); 52 return StatusCode.REQUEST_PARAM_ERROR; 53 } 54 55 if (Long.parseLong(starttime) >= Long.parseLong(endtime)) { 56 logger.info("the starttime less than or equal to endtime"); 57 return StatusCode.ACTIVITY_TIME_ERROR; 58 } 59 60 Activity activity = new Activity(); 61 activity.setActivityname(activityname); 62 activity.setCoverimage(filepath1); 63 activity.setThumbnail(filepath2); 64 activity.setWinrate(Double.valueOf(winrate)); 65 activity.setExpectedwinners(Integer.valueOf(expectedwinners)); 66 activity.setDaysnum(Integer.valueOf(daysnum)); 67 activity.setFirstnum(Integer.valueOf(firstnum)); 68 activity.setSharelimitnum(Integer.valueOf(sharelimitnum)); 69 activity.setFriendclicknum(Integer.valueOf(friendclicknum)); 70 activity.setRuledesc(ruledesc); 71 activity.setStarttime(new Date(Long.parseLong(starttime))); 72 activity.setEndtime(new Date(Long.parseLong(endtime))); 73 activity.setPrizename(prizename); 74 activity.setPrizeprice(Double.valueOf(prizeprice)); 75 activity.setCardid(Integer.valueOf(cardid)); 76 77 int result = activityMapper.addActivity(activity); 78 if (result != 1) { 79 logger.info("add activity fail"); 80 return StatusCode.ADD_ACTIVITY_FAIL; 81 } 82 } catch (Exception e) { 83 logger.error("add activity error", e); 84 return StatusCode.FAIL; 85 } 86 return StatusCode.SUCCESS; 87 } 88 89 /** 90 * 文件上传 91 * @param file 92 * @param savepath 93 * @return 94 */ 95 public String uploadFile(MultipartFile file){ 96 String savepath = Constants.UPLOAD_FILE_IMAGE_SAVE_PATH; 97 File filedir = new File(savepath); 98 //如果文件夹不存在则创建 99 if (!filedir.exists()) { 100 logger.info("create directory:{}", savepath); 101 try{ 102 filedir.mkdirs(); 103 }catch(Exception e){ 104 logger.error("create directory fail", e); 105 return null; 106 } 107 } 108 109 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 110 String nowdate = sdf.format(new Date(System.currentTimeMillis())); 111 112 String originalfilename = file.getOriginalFilename(); 113 if (originalfilename == null || !originalfilename.contains(".")) { 114 logger.info("file name is error:{}", originalfilename); 115 return null; 116 } 117 String suffix = originalfilename.substring(originalfilename.indexOf(".")); 118 String filepath = savepath + nowdate + suffix; 119 120 File targetFile = new File(filepath); 121 try { 122 file.transferTo(targetFile); 123 } catch (Exception e) { 124 logger.error("file upload fail", e); 125 return null; 126 } 127 return filepath; 128 }
使用FORM的话需要指定enctype="multipart/form-data"
附上我测试用的form表单
1 <form action="http://localhost:8080/activity/addActivity" method="post" enctype="multipart/form-data"> 2 activityname<input type="text" name="activityname" value="第一个测试活动"/><br> 3 expectedwinners<input type="text" name="expectedwinners" value="100"/><br> 4 daysnum<input type="text" name="daysnum" value="3"/><br> 5 firstnum<input type="text" name="firstnum" value="5"/><br> 6 sharelimitnum<input type="text" name="sharelimitnum" value="6"/><br> 7 friendclicknum<input type="text" name="friendclicknum" value="7"/><br> 8 ruledesc<input type="text" name="ruledesc" value="这里简单描述下规则,自己写啊。"/><br> 9 starttime<input type="text" name="starttime" value="1519292136927"/><br> 10 endtime<input type="text" name="endtime" value="1519293136927"/><br> 11 prizename<input type="text" name="prizename" value="笔记本电脑"/><br> 12 prizeprice<input type="text" name="prizeprice" value="5999.56"/><br> 13 cardid<input type="text" name="cardid" value="1"/><br> 14 <input type="file" name="file1"/><br> 15 <input type="file" name="file2"/><br> 16 <input type="submit" value="提交"/> 17 </form>