Spring boot集成文件服务(代码示范、Postman传MultipartFile类型参数过程)
一、文件上传接口
/**
* 文件服务
*
* @Author Feng, Ge 2020年3月11日15:22:54
*/
@RestController
@RequestMapping(value = "/file")
@Api(value = "FileController", tags = {"文件服务"})
@Slf4j
public class FileController {
@Value("${fileServer.url}")
private String FILE_SERVER_URL;
/**
* 文件上传接口
* @param file
* @return
* @throws IOException
*/
@RequestMapping("/uploadFileToServer")
@ResponseBody
public JsonResult uploadFileToServer(MultipartFile file) throws IOException, ApiException {
MlyunClient client = new DefaultMlyunClient(FILE_SERVER_URL);
File tempFile = null;
try {
String originalFilename = file.getOriginalFilename();
long size = file.getSize();
String suffix = file.getOriginalFilename().substring(originalFilename.lastIndexOf("."));
tempFile = File.createTempFile("tmp", suffix);
file.transferTo(tempFile);
FileInputStream fileInputStream = new FileInputStream(tempFile);
MultipartFile multipartFile = new MockMultipartFile("file", originalFilename,
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
MlyunResponse rsp = client.execute(new MlyunFSUploadRequest(multipartFile));
System.out.println("【文件服务返回数据】" + rsp.getBody());
Map serverResultMap = JsonUtil.jsonToMap(rsp.getBody());
Map<String,Object> urlMap = new HashMap<>(4);
if(MyUtil.isNotBlank(serverResultMap.get("data"))){
urlMap.put("size", size);
urlMap.put("suffix", suffix);
urlMap.put("url", serverResultMap.get("data"));
urlMap.put("fileName", originalFilename);
return new JsonResult(true, "上传成功!", urlMap);
}else {
return JsonResult.error("上传失败!");
}
} finally {
if (tempFile != null) {
tempFile.deleteOnExit();
}
}
}
}
FILE_SERVER_URL为文件服务器ip+端口,参数类型为MultipartFile。
二、Postman测试
1.设置Headers
key:Content-Type
value:multipart/form-data
2.设置Body为form-data,传参类型选择file类型
3.结果