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

时间:2019-06-10 12:15:51

标签: spring feign

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

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

这不起作用,并以json的形式传递数据,且顶部元素名为file。 如何使用此控制器方法参数注释正确接收另一侧的字节数组?

@RequestBody byte[] file

1 个答案:

答案 0 :(得分:1)

您可以尝试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