How can I get MIME type of an InputStream of a file that is being uploaded?

前端 未结 8 1293
离开以前
离开以前 2020-12-30 21:51

Simple question: how can I get MIME type (or content type) of an InputStream, without saving file, for a file that a user is uploading to my servlet?

8条回答
  •  囚心锁ツ
    2020-12-30 22:08

    If using a JAX-RS rest service you can get it from the MultipartBody.

    @POST
    @Path( "/" )
    @Consumes( "multipart/form-data" )
    public Response importShapeFile( final MultipartBody body ) {
        String filename = null;
        String InputStream stream = null;
        for ( Attachment attachment : body.getAllAttachments() )
        {
            ContentDisposition disposition = attachment.getContentDisposition();
            if ( disposition != null && PARAM_NAME.equals( disposition.getParameter( "name" ) ) )
            {
                filename = disposition.getParameter( "filename" );
                stream = attachment.getDataHandler().getInputStream();
                break;
            }
        }
    
        // Read extension from filename to get the file's type and
        // read the stream accordingly.
    }
    

    Where PARAM_NAME is a string representing the name of the parameter holding the file stream.

提交回复
热议问题