根据业务需求,需提供一个下载kml格式航线文件的HTTP GET接口
示例代码
package com.kyrielx.kmzdemo.controller;import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;/*** @author kyrielx* @date 2024/3/19 9:39* @desc**/
@RestController
@RequestMapping("/kyrielx")
public class DemoController {// 文件上传接口,接收一个file参数@PostMapping("/uploadKmz")public String upload(MultipartFile file) {// 保存MultipartFile类型的文件到本地目录try {// 获取当前项目相对路径地址 target/classesString path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();System.out.println(path + file.getOriginalFilename());file.transferTo(new File( path + file.getOriginalFilename()));} catch (IOException e) {e.printStackTrace();}return "success";}// 文件下载接口@GetMapping(path = "/downloadKmz/{fileName}")public ResponseEntity<byte[]> download(@PathVariable String fileName) {// 将本地文件返回给前端if(null != fileName){try {HttpHeaders headers = new HttpHeaders();headers.setContentDispositionFormData("attachment", new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1"));headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);String path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();System.out.println(path+fileName);File templateFile = new File(path + fileName);return new ResponseEntity<>(FileUtils.readFileToByteArray(templateFile), headers, HttpStatus.CREATED);}catch (Exception e){return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);}}else{return new ResponseEntity<>(HttpStatus.BAD_REQUEST);}}}
测试
经测试,kml和kmz格式的文件均可正常上传下载,response响应体的content-type设置成MediaType.APPLICATION_OCTET_STREAM 即可
InteIlij IDEA AI编程插件推荐
Plugins --> Raccoon (商汤发布的小浣熊),手机号注册登录即可用,挺方便的。
贴一张使用截图: