简体   繁体   中英

How to receive an image send as octet-stream type in the rest service?

I have a rest client that sends a multipart form data. I am sending an image as "application/octet-stream". The image type is JPEG.

How should I correctly receive this in the REST service ?

Currently i am receiving it as InputStream . I converted this input stream to a file,but i am unable to open it.It says error in jpeg while trying to open it.

Input stream to File Conversion logic

File image=File.createTempFile("image", ".JPEG");
FileUtils.copyInputStreamToFile(inputStream, image);

For clarity i am sharing the rest client stub and the rest service implementations.

Rest client stub

public class ImageTest 
{

    public static void main(String[] args) throws IOException 
    {
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget target = client.target("http://localhost:8080/rest/AS/uploadreceipt");

        MultipartFormDataOutput formData = new MultipartFormDataOutput();

        Map<String, Object> json = new HashMap<>();

        json.put("loyaltyId", "23");

        formData.addFormData("json", json, MediaType.APPLICATION_JSON_TYPE);

        FileInputStream fis = new FileInputStream(new File("/root/Downloads/index.jpeg"));

    formData.addFormData("image", fis, MediaType.APPLICATION_OCTET_STREAM_TYPE);

        Entity<MultipartFormDataOutput> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);

        Response response = target.request().post(entity);


    }

Rest service processing

Map<String, Object> json = receiptUploadRequest.getFormDataPart("json", new GenericType<Map<String, Object>>() {});

InputStream image = receiptUploadRequest.getFormDataPart("image", new GenericType<InputStream>() {});

Is there anything i need to consider like headers,etc..because its send as a octet-stream from rest client.something is preventing to create a file.. Can anyone please help me convert the image sent from rest client stub to a file ....

i was setting the input stream object to aa corresponding pojo field.This was causing corruption in the input stream. Hence before setting to a pojo field,i converted the input stream to a file.The file created is perfect now.

Do not invoke fis.read() , because it is consuming the first byte of your image stream.

Maybe you should include in your question the code that transforms client input stream into a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM