java 如何在 Jersey 中获取 MIME 类型的上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4157127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:06:01  来源:igfitidea点击:

How to get MIME type of uploaded file in Jersey

javafile-uploaduploadmime-typesjersey

提问by Cristian Vrabie

I have a standard upload endpoint in Jersey:

我在泽西岛有一个标准的上传端点:

@POST
@Secure
@Consumes("multipart/form-data")
public Response upload( @Context final HttpHeaders hh,
            @FormDataParam("fileaaa") final FormDataContentDisposition disposition,
            @FormDataParam("fileaaa") final InputStream input,

How can I get the MIME type of the uploaded file?

如何获取上传文件的 MIME 类型?

If I do disposition.getTypethis gets me the MIME type of the form; in this case form-data.

如果我这样做disposition.getType,我将获得表单的 MIME 类型;在这种情况下form-data

I know the information is there somewhere; the HTTP message should be something like:

我知道信息在某处;HTTP 消息应该是这样的:

-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="input_text"

mytext

-----------------------------7d01ecf406a6
Content-Disposition: form-data; name="fileaaa";
filename="C:\Inetpub\wwwroot\Upload\pic.gif"
Content-Type: image/gif

(binary content)
-----------------------------7d01ecf406a6--

回答by Cristian Vrabie

I solved this by letting Jersey inject a BodyPartparameter in my method. getMediaType() on the body part gives me what I needed:

我通过让 Jersey在我的方法中注入一个BodyPart参数来解决这个问题。身体部位的 getMediaType() 给了我我需要的东西:

@POST
@Secure
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(/*other parms */,  @FormDataParam("fileaaa") final FormDataBodyPart body) {
   String mimeType = body.getMediaType().toString();
   //handle upload
}