环境:
系统环境:win10
开发工具:IntelliJ IDEA 2021.3.2
测试工具:Postman
注解:
@RestController:将@ResponseBody与@Controller合并成了一个注解来用。
@CrossOrigin:支持跨域。
@SpringBootApplication:设置启动项
端口号设置:server.port=8080
pom.xml:
这里用到了解析xml
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.1</version> </dependency>
文件操作,所以需要将上传的【MultipartFile】类型的对象转换成【File】,这里单独添加了一个方法。
这里留了注释,可以直接使用,没什么好解释的。
/** * 将MultipartFile对象转换成File文件 * @param multipartFile * @return */ public static File MultipartFileToFile(MultipartFile multipartFile) { File file = null; //判断是否为null if (multipartFile.equals("") || multipartFile.getSize() <= 0) { return file; } //MultipartFile转换为File InputStream ins = null; OutputStream os = null; try { ins = multipartFile.getInputStream(); file = new File(multipartFile.getOriginalFilename()); os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException e) { e.printStackTrace(); } } } return file; }
测试编码:
@PostMapping(value = "/api/Index") public Object Index(MultipartFile files) { if (files.getSize() == 0) { return new ERROR("格式化失败", null); } Document document = null; SAXReader saxReader = new SAXReader(); try { document = saxReader.read(MultipartFileToFile(files)); Element root = document.getRootElement(); System.out.println(root); return new SUCCESS("格式化成功", root); } catch (Exception ex) { ex.printStackTrace(); } return new ERROR("数据结构异常", null);
返回对象
class BackResult { public BackResult(String message, Object result) { this.state = true; this.message = message; this.result = result; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } public boolean state; public String message; public Object result; } class SUCCESS extends BackResult { public SUCCESS(String message, Object result) { super(message, result); this.state = true; } } class ERROR extends BackResult { public ERROR(String message, Object result) { super(message, result); this.state = false; } }
上传文件测试:
访问方式【POST】,访问路径【http://127.0.0.1:8080/api/Index】,这里面我给操作步骤了,挨个点就行,如果的图片就直接读取,其它文件类型就解析即可。