【问题标题】:How can receive multiple files in InputStream and process it accordingly?如何在 InputStream 中接收多个文件并进行相应处理?
【发布时间】:2014-05-01 13:40:52
【问题描述】:

我想接收从我的客户端上传的多个文件。我上传了多个文件并使用 JAX-RS(Jersey) 请求我的服务器端 (Java)。

我有以下代码,

@POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void upload(@Context UriInfo uriInfo,
            @FormDataParam("file") final InputStream is,
            @FormDataParam("file") final FormDataContentDisposition detail) {
FileOutputStream os = new FileOutputStream("Path/to/save/" + appropriatefileName);
    byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
}

如何在服务器端单独编写文件在客户端上传。

例如。我上传了My_File.txt, My_File.PNG, My_File.doc等文件。 我需要在服务器端写和上面的My_File.txt, My_File.PNG, My_File.doc一样。

我怎样才能做到这一点?

【问题讨论】:

    标签: java file jersey jax-rs inputstream


    【解决方案1】:

    【讨论】:

    • 那篇博文看起来不错,但它直接处理 HttpServletRequest 并使用外部库 (commons-fileupload) 来处理文件上传。 FormDataMultiPart 内置于球衣中,使用起来可能更简单
    【解决方案2】:

    你可以试试这样的:

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public void upload(FormDataMultiPart formParams)
    {
        Map<String, List<FormDataBodyPart>> fieldsByName = formParams.getFields();
    
        // Usually each value in fieldsByName will be a list of length 1.
        // Assuming each field in the form is a file, just loop through them.
    
        for (List<FormDataBodyPart> fields : fieldsByName.values())
        {
            for (FormDataBodyPart field : fields)
            {
                InputStream is = field.getEntityAs(InputStream.class);
                String fileName = field.getName();
    
                // TODO: SAVE FILE HERE
    
                // if you want media type for validation, it's field.getMediaType()
            }
        }
    }
    

    【讨论】:

    • @奥尔登。我没有得到 getName() 这种方式。此外,如果我传递一个对象,我会得到 NullPointer。请您再解释一下。
    猜你喜欢
    • 1970-01-01
    • 2019-01-05
    • 2018-06-10
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2021-05-08
    • 2019-12-08
    相关资源
    最近更新 更多