Java – how do I receive multiple files in InputStream and process them accordingly?
•
Java
I want to receive multiple files uploaded from the client I uploaded multiple files and requested my server (Java) using Jax - RS (Jersey)
I have the following code,
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) public void upload(@Context UriInfo uriInfo,@FormDataParam("file") final InputStream is,@FormDataParam("file") final FormDataContentDisposition detail) { FileOutputStream os = new FileOutputStream("Path/to/save/" + appropriatefileName); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer,length); } }
How to write files separately on the server side uploaded by the client
For example I uploaded my_ File. txt,My_ File. PNG,My_ File. Doc and other documents I need to write my on the server side_ File. txt,My_ File. Doc
How can I do this?
Solution
You can try something like this:
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) public void upload(FormDataMultiPart formParams) { Map<String,List<FormDataBodyPart>> fieldsByName = formParams.getFields(); // Usually each value in fieldsByName will be a list of length 1. // Assuming each field in the form is a file,just loop through them. for (List<FormDataBodyPart> fields : fieldsByName.values()) { for (FormDataBodyPart field : fields) { InputStream is = field.getEntityAs(InputStream.class); String fileName = field.getName(); // TODO: SAVE FILE HERE // if you want media type for validation,it's field.getMediaType() } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码