简体   繁体   中英

How do i parse content sent from multipart/form-data request to get file in java?

I am sending a HttpURLConnection request to server and trying to send a file. I am able to send file from client side but not sure how can i parse it on the server side.

My code on client side is below.

private void createRequestInCHESS(String sRequestId, String sLastUpdated) {
        String boundary =  "xyz";
        String crlf = "\r\n";
        String twoHyphens = "--";
        String attachmentName = "file";
        String attachmentFileName = "testFile.xlsx";
        try {
            File file = new File("c:\\MFGREQ-7.xlsx");
            URL url = new URL(chess.getMfgRequestURL() + "/createRequest");
            HttpURLConnection httpConnecton = (HttpURLConnection) url.openConnection();
            httpConnecton.setRequestMethod(REQUEST_METHOD_POST);
            httpConnecton.setRequestProperty("Accept", "application/json");
            httpConnecton.setRequestProperty("Cache-Control", "no-cache");
            httpConnecton.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            httpConnecton.setRequestProperty("id", sRequestId);
            httpConnecton.setRequestProperty("lastModified", sLastUpdated);     
                        
            httpConnecton.setDoOutput(true);
                
            
            
            DataOutputStream outStream = new DataOutputStream(httpConnecton.getOutputStream());
            outStream.writeBytes(twoHyphens + boundary + crlf);
            outStream.writeBytes("Content-Disposition: form-data; name=\"" +
                attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
            outStream.writeBytes(crlf);
            
            byte[] bytes = Files.readAllBytes(file.toPath());
            outStream.write(bytes);
            
            outStream.flush();
            outStream.close();
            getResponseString(httpConnecton);
            
        } catch (MalformedURLException me) {
            me.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

server side code is given below. What can I use to retrive file sent from request.

@POST
    @Path("/createRequest")
    public Response createRequest(@Context HttpServletRequest request) {

        try(BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getInputStream()))) {             
            StringBuilder sbPayload = new StringBuilder();
            String sLine;
            while ((sLine = reader.readLine()) != null) {
                sbPayload.append(sLine);
                sbPayload.append(System.lineSeparator());
            }

            String data = sbPayload.toString();

          // how do i retrieve file here ?

}

You really don't want to parse that yourself. Use the https://commons.apache.org/proper/commons-fileupload/

Then you can just write.

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8"); // Might be needed, depending on exact setup.
java.util.List<FileItem> items = upload.parseRequest(request);

And then items is the list of uploaded files.

Here is my answer. I have used org.glassfish.jersey.media.multipart.MultiPart on client side.

    Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
            WebTarget webTarget = client.target(chess.getMfgRequestURL() + "/createRequest")
                    .queryParam("id", sRequestId)
                    .queryParam("lastModified", sLastUpdated);
            
            FileDataBodyPart fileDataBodyPart = new FileDataBodyPart("file",
                    file, MediaType.APPLICATION_OCTET_STREAM_TYPE);
            @SuppressWarnings("resource")
            MultiPart multiPart = new FormDataMultiPart()
                    .field("json", jsonObj, MediaType.APPLICATION_JSON_TYPE) // json goes here
                    .bodyPart(fileDataBodyPart); // file goes here
            
            multiPart.bodyPart(fileDataBodyPart);
            
            Response response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
                      .post(Entity.entity(multiPart, multiPart.getMediaType()));

On server side, this is how I have parsed:

 @POST
    @Path("/createRequest")
    @Consumes("multipart/form-data")
    public Response createRequest(@Context HttpServletRequest request,  @Multipart InputStream uploadedInputStream) throws Exception {
        JsonObjectBuilder requestBuilder = null;
        try {
            
            String tempDir = "C:\\Users";
            String filename = "test.xlsx";

            File checkinFile = new File(tempDir, filename);
            OutputStream out = new FileOutputStream(checkinFile);
            IOUtils.copyStream(uploadedInputStream, out);        
        }catch (Exception e) {
            String errorMessage = e.getMessage();
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
        }

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