Springboot+HTML5+Layui2.7.6上传文件【请求上传接口出现异常】
1.最近两天在springboot+html5项目中发现在用layui框架时报请求上传接口出现异常这个错误。
2.将代码全部整理了一遍,发现前端后台都没错!!!
但是还是【请求上传接口出现异常】,于是跑去翻看layui官网。
3.最终最终将错误锁定到了返回的JSON字符串中,我是返回的String,所以一直都会报【请求上传接口出现异常】。
4.可以在controller中将其返回成JSON字符串。
<1>首先我们要导入一个依赖
<!-- fast json--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency>
<2>在controller中修改成上传成功返回JSON字符串
@PostMapping("/uploadFile") @ResponseBody public HashMap<String, Object> singleFileUpload(@RequestParam("file") MultipartFile file) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("fileName = {}", file.getOriginalFilename()); } try { if (file == null || NULL_FILE.equals(file.getOriginalFilename())) { // return "upload failure"; return ResultMapUtil.getHashMapUploadFile("upload failure","500"); } fileService.saveFile(file.getBytes(), uploadFolder, file.getOriginalFilename()); } catch (Exception e) { // return "upload failure"; return ResultMapUtil.getHashMapUploadFile("upload failure","500"); } // return "upload success"; return ResultMapUtil.getHashMapUploadFile("upload success","200"); }
【注意:这一步中不同的人写的项目不同,controller也不相同,需要自己的根据实际情况来】
<3>给前端返回JSON格式数据
/** * 给前端返回的json格式数据 */ public class ResultMapUtil { // 上传文件返回结果 public static HashMap<String,Object> getHashMapUpload(String msg, String code){ HashMap<String,Object> resultMap = new HashMap<>(); resultMap.put("msg",msg); resultMap.put("code",code); if("200".equals(code)){ resultMap.put("msg","success"); }else { resultMap.put("msg","failure"); } return resultMap; } }
<4>文件上传service文件
@Service @Transactional public class FileServiceImpl implements FileService { private static final String UTF_8 = "UTF-8"; @Value("${file.uploadFolder}") private String uploadFolder; @Override public void saveFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); } }
<5>文件上传service实现类文件
@Service @Transactional public class FileServiceImpl implements FileService { private static final String UTF_8 = "UTF-8"; @Value("${file.uploadFolder}") private String uploadFolder; @Override public void saveFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); } }