How do I do a multipart/form file upload with jax-rs?

后端 未结 1 741
孤独总比滥情好
孤独总比滥情好 2020-12-02 11:44

(specifically RESTeasy)

It would be nice (for a single file) to have a method signature like:

public void upload(@FormParam(\"name\") ..., @FormPar         


        
相关标签:
1条回答
  • 2020-12-02 12:22

    The key is to leverage the @MultipartForm annotations that comes with RESTEasy. This enables you to define a POJO that contains all the parts of the form and bind it easily.

    Take for example the following POJO:

    public class FileUploadForm {
        private byte[] filedata;
    
        public FileUploadForm() {}
    
        public byte[] getFileData() {
            return filedata;
        }
    
        @FormParam("filedata")
        @PartType("application/octet-stream")
        public void setFileData(final byte[] filedata) {
            this.filedata = filedata;
        }
    }
    

    Now all you need to do is use this POJO in the entity which would look something like this:

    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response create(@MultipartForm FileUploadForm form) 
    {
        // Do something with your filedata here
    }
    
    0 讨论(0)
提交回复
热议问题