@MultipartForm How to get the original file name?

前端 未结 3 855
挽巷
挽巷 2021-02-19 23:54

I am using jboss\'s rest-easy multipart provider for importing a file. I read here http://docs.jboss.org/resteasy/docs/1.0.0.GA/userguide/html/Content_Marshalling_Providers.html

3条回答
  •  别跟我提以往
    2021-02-20 00:37

    After looking around a bit for Resteasy examples including this one, it seems like there is no way to retrieve the original filename and extension information when using a POJO class with the @MultipartForm annotation.

    The examples I have seen so far retrieve the filename from the Content-Disposition header from the "file" part of the submitted multiparts form data via HTTP POST, which essentially, looks something like:

    Content-Disposition: form-data; name="file"; filename="your_file.zip"
    Content-Type: application/zip
    

    You will have to update your file upload REST service class to extract this header like this:

    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response uploadFile(MultipartFormDataInput input) {
    
      String fileName = "";
      Map> formParts = input.getFormDataMap();
    
      List inPart = formParts.get("file"); // "file" should match the name attribute of your HTML file input 
      for (InputPart inputPart : inPart) {
        try {
          // Retrieve headers, read the Content-Disposition header to obtain the original name of the file
          MultivaluedMap headers = inputPart.getHeaders();
          String[] contentDispositionHeader = headers.getFirst("Content-Disposition").split(";");
          for (String name : contentDispositionHeader) {
            if ((name.trim().startsWith("filename"))) {
              String[] tmp = name.split("=");
              fileName = tmp[1].trim().replaceAll("\"","");          
            }
          }
    
          // Handle the body of that part with an InputStream
          InputStream istream = inputPart.getBody(InputStream.class,null);
    
          /* ..etc.. */
          } 
        catch (IOException e) {
          e.printStackTrace();
        }
      }
    
      String msgOutput = "Successfully uploaded file " + filename;
      return Response.status(200).entity(msgOutput).build();
    }
    

    Hope this helps.

提交回复
热议问题