没有前言,直接进入正题
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
编写配置类
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
* 文件传输配置
*/
@Component
@RequiredArgsConstructor(onConstructor = @__(
@Autowired
))
public class MultipartSupportConfig {
final ObjectFactory<HttpMessageConverters> messageConverters;
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
feign接口编写
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* 工具类
* 这里一定要指定feign使用的配置文件
*/
@FeignClient(value = "tool", configuration = {MultipartSupportConfig.class}, url = "{}")
public interface ToolFeignClient {
/**
* 上传文件
*
* @param files 文件列表
* @return List<String>
*/
@PostMapping(value = "/oss/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
List<String> uploadFile(@RequestPart MultipartFile[] file);
}
注意,这里一定要使用@RequestPart还有consumes一定要指定,否则会默认使用application/json进行传递,会导致json序列化错误
下层服务
这里是直接返回的存储后的路径
import com.hb.shop.tool.oss.service.IOssService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
/**
* OSS文件处理
**/
@RestController
@RequestMapping("/oss")
@RequiredArgsConstructor(onConstructor = @__(
@Autowired
))
public class OssController {
/**
* 文件上传服务
*/
final IOssService ossService;
/**
* 上传文件
* @param file 文件列表
* @return List<String>
*/
@PostMapping("/upload")
@ApiOperation(value = "上传图片接口",notes = "上传图片接口")
public List<String> upload(@RequestPart MultipartFile[] file) {
return ossService.upload(file);
}
}
我这里是直接上传好之后,将文件存储的路径返回,传入与传出的是文件数组,也可以传入单个文件,根据业务情况而定即可