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

Kri*_*nya 9 java jboss web-services java-ee resteasy

我正在使用jboss的rest-easy multipart提供程序来导入文件.我在这里阅读http://docs.jboss.org/resteasy/docs/1.0.0.GA/userguide/html/Content_Marshalling_Providers.html#multipartform_annotation关于@MultipartForm,因为我可以用我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我需要在服务器端提供此信息,以便我可以正确应用un-archive程序.

原始文件名以content-disposition标头发送到服务器.

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

iva*_*sim 14

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

到目前为止我看到的示例Content-Disposition通过HTTP POST从提交的多部分表单数据的"文件"部分的头部检索文件名,基本上看起来像:

Content-Disposition: form-data; name="file"; filename="your_file.zip"
Content-Type: application/zip
Run Code Online (Sandbox Code Playgroud)

您必须更新文件上载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();
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


lef*_*loh 5

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

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