Upload data file as byte array with Feign

Zveratko :

How can I send file in Feign as byte array?

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

This is not working and passing the data in form of json with top element named file. What can I do to properly receive array of bytes on the other side using this controller method parameter annotation?

@RequestBody byte[] file
tsarenkotxt :

You can try OpenFeign/feign-form, simple example:

pom.xml dependencies

    <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);
        }

    }

}

response output:

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

also @RequestBody it's annotation for REST json body, for files:

@RequestParam("file") MultipartFile file

take a loot at Spring Boot Uploading Files

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

Write Byte Array to a file Javascript

Volley - download directly to file (no in memory byte array)

Reading hexadecimal data into byte array in Java?

How to save []byte data in array list

How to send byte array data to other activities?

python requests upload large file with additional data

Can I read a byte array from file using scanner?

Использование абстрактных запросов с Feign

Feign - определите значение параметра для каждого метода

Reading raw byte data from a file and decoding it to a protobuf structs

File not upload

Object to ByteString \ Byte Array

convert a byte array to string

scala Array [Byte] diff

ByteBuffer y Byte Array

Convert a byte array to a string array

When downloading a file from a URL, why do we read into a byte array?

How to convert video/audio file to byte array and vice versa in android.?

Problems to write a byte array of a signed hash with a private key in a text file and get it back as the same format

JSON .txt File in Data to Convert Array

Passing php array data to a js file

How to read data from a file into an array of a class

Comparison of byte instances and byte array instances

ioutil.ReadAll alternative that only consumes data, without duplicating the byte array

Will data be copied byte by byte when moving a variable?

Loading data range or string from excel file to an array then split in array

Carga de archivos usando Feign - multipart / form-data

Upload StorageFile to a PHP File

Upload file to SharePoint