臨近年關,本來想做完本地存儲的這個需求,再完成另一個需求,就可以溜之大吉的了。想不到突然老大說要整合一下你現在做的服務,給外部服務調用你服務的上傳下載接口。然後……
好了,說回跨服務的文件上傳下載操作。
1.跨服務文件上傳,目前feign不支持調用文件上傳接口,需要自行配置來滿足feign的調用方式
①首先需要在pom文件裏添加feign依賴
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.2.2</version>
</dependency>
②上傳的接口
@FeignClient(value = "fdn-storage", configuration = {FileFeignConfig.class})
public interface FileClient {
String PREFIX_PATH = "/oss/files";
/**
* 上傳存儲文件
* @param file
* @return
* @throws IOException
*/
@PostMapping(value = PREFIX_PATH + "/", consumes = MULTIPART_FORM_DATA_VALUE)
FeignResult<FileEntity> save(@RequestPart(value = "file") MultipartFile file) throws IOException;
}
③添加配置來滿足feign的調用
@Configuration
public class FileFeignConfig {
@Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
@Primary
@Scope("prototype")
public Encoder feignEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
@Bean
public feign.Logger.Level multipartLoggerLevel() {
return feign.Logger.Level.FULL;
}
}
④外部服務的controller層調用
public class TestController extends BaseRestController {
@Autowired
FileClient client;
/**
* 上傳文件
**/
@PostMapping(value = "/" , consumes = MULTIPART_FORM_DATA_VALUE)
public FileEntity save(@RequestPart(value = "file") MultipartFile file) throws IOException {
FileEntity fileEntity = client.save(file).getData();
return fileEntity;
}
}
到此位置就可以上傳成功了
2.跨服務的文件下載
①下載的接口(也是寫在public interface FileClient),是用feign.Response來作爲返回值的
/**
* 下載文件
* @param id
* @return
* @throws IOException
*/
@GetMapping(value = PREFIX_PATH + "/{id}/data")
Response download(@PathVariable("id") String id) throws IOException;
②外部服務的controller層調用
/**
*由id下載存儲的文件
*/
@GetMapping(value = "/{id}/data")
public void downloadFile(@PathVariable String id, HttpServletResponse servletResponse) throws IOException {
Response response = client.download(id);
Response.Body body = response.body();
for(Object key : response.headers().keySet()){
List<String> kList = (List)response.headers().get(key);
for(String val : kList){
servletResponse.setHeader(StringUtils.toString(key), val);
}
}
try(InputStream inputStream = body.asInputStream();
OutputStream outputStream = servletResponse.getOutputStream()
){
byte[] b = new byte[inputStream.available()];
inputStream.read(b);
outputStream.write(b);
outputStream.flush();
}catch (IOException e){
throw new RestException("IO流異常", e);
}
}
至此,下載文件完成。