java @MultipartForm 如何获取原始文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26333298/
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-11-02 09:43:48  来源:igfitidea点击:

@MultipartForm How to get the original file name?

javaweb-servicesjakarta-eejbossresteasy

提问by Krishna Chaitanya

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#multipartform_annotationregarding @MultipartForm because I can exactly map it with my POJO.

我正在使用 jboss 的 rest-easy 多部分提供程序来导入文件。我在这里阅读了关于@MultipartForm 的http://docs.jboss.org/resteasy/docs/1.0.0.GA/userguide/html/Content_Marshalling_Providers.html#multipartform_annotation,因为我可以将它与我的 POJO 准确映射。

Below is my POJO

下面是我的 POJO

public class SoftwarePackageForm {

    @FormParam("softwarePackage")
    private File file;

    private String contentDisposition;

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getContentDisposition() {
        return contentDisposition;
    }

    public void setContentDisposition(String contentDisposition) {
        this.contentDisposition = contentDisposition;
    }
}

Then I got the file object and printed its absolute path and it returned a file name of type file. The extension and uploaded file name are lost. My client is trying to upload a archive file(zip,tar,z)

然后我得到了文件对象并打印了它的绝对路径,它返回了一个文件类型的文件名。扩展名和上传的文件名丢失。我的客户正在尝试上传存档文件(zip、tar、z)

I need this information at the server side so that I can apply the un-archive program properly.

我在服务器端需要此信息,以便我可以正确应用取消归档程序。

The original file name is sent to the server in content-disposition header.

原始文件名在 content-disposition 标头中发送到服务器。

How can I get this information? Or atleast how can I say jboss to save the file with the uploaded file name and extension? Is it configurable from my application?

我怎样才能得到这些信息?或者至少我怎么能说 jboss 用上传的文件名和扩展名保存文件?它可以从我的应用程序配置吗?

回答by ivan.sim

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 @MultipartFormannotation.

环视了一下对RestEasy的例子包括在此之后一个,好像是没有办法使用与一个POJO类时恢复原始文件名和扩展信息@MultipartForm的注释。

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

到目前为止,我所看到的示例Content-Disposition通过 HTTP POST 从提交的多部分表单数据的“文件”部分的标头中检索文件名,本质上类似于:

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:

您必须更新您的文件上传 REST 服务类以提取此标头,如下所示:

@POST
@Path("/upload")
@Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) {

  String fileName = "";
  Map<String, List<InputPart>> formParts = input.getFormDataMap();

  List<InputPart> 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<String, String> 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.

希望这可以帮助。

回答by lefloh

You could use @PartFilenamebut unfortunately this is currently only used for writing forms, not reading forms: RESTEASY-1069.

您可以使用@PartFilename但不幸的是,这目前仅用于编写表单,而不是读取表单:RESTEASY-1069

Till this issue is fixed you could use MultipartFormDataInputas parameter for your resource method.

在修复此问题之前,您可以将其MultipartFormDataInput用作资源方法的参数。

回答by Αλ?κο?

It seems that Isim is right, but there is a workaround.

似乎 Isim 是对的,但有一个解决方法。

Create a hidden field in your form and update its value with the selected file's name. When the form is submitted, the filename will be submitted as a @FormParam.

在表单中创建一个隐藏字段并使用所选文件的名称更新其值。提交表单时,文件名将作为@FormParam 提交。

Here is some code you could need (jquery required).

这是您可能需要的一些代码(需要 jquery)。

<input id="the-file" type="file" name="file">
<input id="the-filename" type="hidden" name="filename">

<script>
$('#the-file').on('change', function(e) {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf('\');
    if (lastIndex < 0) {
        lastIndex = filename.lastIndexOf('/');
    }
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    $('#the-filename').val(filename);
});
</script>