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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (573)

如何在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
提问于
用户回答回答于

您可以尝试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 body的注释,用于文件:

@RequestParam("file") MultipartFile file

Spring Boot上传文件中获取战利品

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励