上传文件
(1)工具类
@UtilityClass
public class MultipartFileUtils {
private static final String FILE_DIR = "C:\\test";
static {
makeSurePathExists();
}
@SneakyThrows
public static void saveFile(MultipartFile file) {
// 使用 commons-io 依赖中的 FileUtils 工具类
// SpringBoot 中已经包含了 commons-io 依赖
FileUtils.copyInputStreamToFile(file.getInputStream(), newDestinationFile(file));
}
private static File newDestinationFile(MultipartFile file) {
String fileName = FILE_DIR + File.separator + file.getOriginalFilename();
return new File(fileName);
}
private static void makeSurePathExists() {
File path = new File(FILE_DIR);
if (!path.exists()) {
path.mkdirs();
}
}
}
(2)定义接口
@RestController
@Slf4j
@RequiredArgsConstructor
public class ImageController {
@PostMapping(value = "/image/upload")
public String upload(@RequestParam("image") MultipartFile file) {
log.info("fileName: {}, originalFilename:{}, contentType:{}, size:{}", file.getName(), file.getOriginalFilename(), file.getContentType(), file.getSize());
MultipartFileUtils.saveFile(file);
return "done";
}
}
(3)调用 http://localhost:8080/image/upload
进行测试。
在目标文件夹中会出现上传的文件。
Feign 调用上传文件接口
(1)定义一个 FeignClient
。
@FeignClient(value = "image", url = "http://127.0.0.1:8080")
public interface ImageClient {
@PostMapping(value = "/image/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
String upload(@RequestPart("image") MultipartFile file);
}
注意事项:
- 使用
@RequestPart
,而不是@RequestParam
- 添加
consumes = MediaType.MULTIPART_FORM_DATA_VALUE
,其值为"multipart/form-data"
(2)调用上面定义的 FeignClient
接口。
@SneakyThrows
@GetMapping("/test")
public void test() {
FileInputStream inputStream = new FileInputStream("C:\\Users\\meikai\\Desktop\\QQ截图20210811101712.png");
MultipartFile multipartFile = new MockMultipartFile("any", "originalFilename.png", null, inputStream);
String result = imageClient.upload(multipartFile);
log.info("upload result: {}", result);
}
(3)调用 http://localhost:8080/test
接口,控制台输出如下:
2021-08-31 19:11:43.804 INFO 24284 --- [nio-8080-exec-6] c.e.demo.controller.ImageController : fileName: image, originalFilename:originalFilename.png, contentType:image/png, size:3315
2021-08-31 19:11:43.806 INFO 24284 --- [nio-8080-exec-5] c.e.demo.controller.ImageController : upload result: done
说明一切正常。
网友评论