文件/图片上传示例
1 <form role="form" method="post" enctype="multipart/form-data" action="/seller/product/upload"> 2 <div class="form-group"> 3 <label>图片</label> 4 <input name="file" type="file"/> 5 </div> 6 <button type="submit" class="btn btn-default">提交</button> 7 </form>
/** * 文件上传 */ @PostMapping("/upload") public static String upload(@RequestParam("file") MultipartFile file){ if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getOriginalFilename(); log.info("上传的文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); log.info("上传的后缀名为:" + suffixName); // 文件上传后的路径 String filePath = "F://test//"; // 解决中文问题,liunx下中文路径,图片显示问题 // fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return dest.toString(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上传失败"; }