使用 Feign 将数据文件上传为字节数组

Upload data file as byte array with Feign

如何在 Feign 中将文件作为字节数组发送?

@RequestLine("POST /api/files/{num}/push")
    @Headers({"Content-Type: application/zip"})
    void pushFile(@Param("num") String num, @Param("file") byte[] file);

这不起作用并以 json 形式传递数据,顶部元素名为文件。 我该怎么做才能使用此控制器方法参数注释在另一端正确接收字节数组?

@RequestBody byte[] file

你可以试试OpenFeign/feign-form,简单的例子:

pom.xml 依赖项

    <dependencies>
        <!--feign dependencies-->
        <dependency>
            <groupId>io.github.openfeign.form</groupId>
            <artifactId>feign-form</artifactId>
            <version>3.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>10.1.0</version>
        </dependency>
        <!--jetty to dependencies to check feign request-->
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-server</artifactId>
            <version>9.4.3.v20170317</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlet</artifactId>
            <version>9.4.3.v20170317</version>
        </dependency>
    </dependencies>

FeignUploadFileExample.java:

import feign.*;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Type;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

public class FeignUploadFileExample {

    public static void main(String[] args) throws Exception {
        // start jetty server to check feign request
        startSimpleJettyServer();

        SimpleUploadFileApi simpleUploadFileApi = Feign.builder()
                .encoder(new SimpleFileEncoder())
                .target(SimpleUploadFileApi.class, "http://localhost:8080/upload");

        // upload file bytes (simple string bytes)
        byte[] fileBytes = "Hello World".getBytes();
        String response = simpleUploadFileApi.uploadFile(fileBytes);

        System.out.println(response);
    }

    public static final String FILE_PARAM = "file";

    // encode @Param("file") to request body bytes
    public static class SimpleFileEncoder implements Encoder {

        public void encode(Object object, Type type, RequestTemplate template) 
                throws EncodeException {
            template.body(Request.Body.encoded(
    (byte[]) ((Map) object).get(FILE_PARAM), UTF_8));
        }

    }

    // feign interface to upload file
    public interface SimpleUploadFileApi {

        @RequestLine("POST /upload")
        @Headers("Content-Type: application/zip")
        String uploadFile(@Param(FILE_PARAM) byte[] file);

    }

    // embedded jetty server
    public static void startSimpleJettyServer() throws Exception {
        Server server = new Server(8080);
        ServletContextHandler handler = new ServletContextHandler(server, "/upload");
        handler.addServlet(SimpleBlockingServlet.class, "/");
        server.start();
    }

    // simple servlet get request and return info of received data
    public static class SimpleBlockingServlet extends HttpServlet {

        protected void doPost(
                HttpServletRequest request,
                HttpServletResponse response) throws IOException {

            String data = new BufferedReader(
                    new InputStreamReader(request.getInputStream())).readLine();

            response.setStatus(HttpStatus.OK_200);

            response.getWriter().println("Request header 'Content-Type': " +
                    request.getHeaders("Content-Type").nextElement());
            response.getWriter().println("Request downloaded file data: " + data);
        }

    }

}

响应输出:

Request header 'Content-Type': application/zip
Request downloaded file data: Hello World

也是 @RequestBody 它是 REST json 主体的注释,对于文件:

@RequestParam("file") MultipartFile file

看看Spring Boot Uploading Files

您可以使用 feign-form 中的 FormData 上传文件并指定 Content-typename:

<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.8.0</version>
</dependency>
@RequestLine("POST /api/files/{num}/push")
void pushFile(@Param("num") String num, @Param("file") FormData file);

用法示例:

byte[] bytes = getFileContent();
FormData file = new FormData("application/zip", "example.zip", bytes);
client.pushFile(num, file);

或者如果您使用的是 spring-cloud-starter-openfeign

@PostMapping("/api/files/{num}/push")
void pushFile(@PathVariable String num, @RequestPart FormData file);

针对 spring-cloud-starter-openfeign 进行了测试,但考虑到 FormData class 生活在 form-data 依赖中,我认为它在没有 spring 的情况下也能正常工作。