RESTlet:如何处理多部分/表单数据请求?

发布于 2024-07-23 12:16:20 字数 389 浏览 4 评论 0原文

当它是多部分/表单数据请求时,如何捕获传入的 @Post 变量?

对于常规的 Post 请求,我会这样做:

@Post
public void postExample(Representation entity) throws Exception{
   Form form = new Form(entity);
   System.out.println(form.getFirstValue("something"));
}

但是因为它是一个 multipart/form-data 请求,所以上面的输出 null

我是 Java 新手,所以要温柔:)

PS:我不感兴趣处理传入的文件,仅处理文本字段。

How do you catch incoming @Post variables when it is a multipart/form-data request?

For a regular Post request I would do:

@Post
public void postExample(Representation entity) throws Exception{
   Form form = new Form(entity);
   System.out.println(form.getFirstValue("something"));
}

But because it is a multipart/form-data request the above outputs null

I'm a Java newbie so be gentle :)

PS: I'm not interested in processing the incoming files, just the text fields.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小猫一只 2024-07-30 12:16:20

这是我的方法之一(Restlet 2.0)的粘贴。 这里我有一个包含一个文件上传和其他字段的表单,因此它相当完整:

@Post
public Representation createTransaction(Representation entity) {
    Representation rep = null;
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            // 1/ Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            // 2/ Create a new file upload handler
            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;
            try {
                // 3/ Request is parsed by the handler which generates a list of FileItems
                items = upload.parseRequest(getRequest());

                Map<String, String> props = new HashMap<String, String>();
                File file = null;
                String filename = null;

                for (final Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
                    FileItem fi = it.next();
                    String name = fi.getName();
                    if (name == null) {
                        props.put(fi.getFieldName(), new String(fi.get(), "UTF-8"));
                    } else {
                        String tempDir = System.getProperty("java.io.tmpdir");
                        file = new File(tempDir + File.separator + "file.txt");
                        filename = name;
                        fi.getInputStream();
                        fi.write(file);
                    }
                }

                // [...] my processing code

                String redirectUrl = ...; // address of newly created resource
                getResponse().redirectSeeOther(redirectUrl);
            } catch (Exception e) {
                // The message of all thrown exception is sent back to
                // client as simple plain text
                getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                e.printStackTrace();
                rep = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
            }
        } else {
            // other format != multipart form data
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            rep = new StringRepresentation("Multipart/form-data required", MediaType.TEXT_PLAIN);
        }
    } else {
        // POST request with no entity.
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        rep = new StringRepresentation("Error", MediaType.TEXT_PLAIN);
    }

    return rep;
}

我最终会将其重构为更通用的内容,但这就是我现在所拥有的。

This is a paste from one of my methods (Restlet 2.0). Here I have a form that includes one file upload plus other fields, therefore it is rather complete:

@Post
public Representation createTransaction(Representation entity) {
    Representation rep = null;
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            // 1/ Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            // 2/ Create a new file upload handler
            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;
            try {
                // 3/ Request is parsed by the handler which generates a list of FileItems
                items = upload.parseRequest(getRequest());

                Map<String, String> props = new HashMap<String, String>();
                File file = null;
                String filename = null;

                for (final Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
                    FileItem fi = it.next();
                    String name = fi.getName();
                    if (name == null) {
                        props.put(fi.getFieldName(), new String(fi.get(), "UTF-8"));
                    } else {
                        String tempDir = System.getProperty("java.io.tmpdir");
                        file = new File(tempDir + File.separator + "file.txt");
                        filename = name;
                        fi.getInputStream();
                        fi.write(file);
                    }
                }

                // [...] my processing code

                String redirectUrl = ...; // address of newly created resource
                getResponse().redirectSeeOther(redirectUrl);
            } catch (Exception e) {
                // The message of all thrown exception is sent back to
                // client as simple plain text
                getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                e.printStackTrace();
                rep = new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
            }
        } else {
            // other format != multipart form data
            getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
            rep = new StringRepresentation("Multipart/form-data required", MediaType.TEXT_PLAIN);
        }
    } else {
        // POST request with no entity.
        getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        rep = new StringRepresentation("Error", MediaType.TEXT_PLAIN);
    }

    return rep;
}

I'll end up refactoring it to something more generic, but this is what I have by now.

最初的梦 2024-07-30 12:16:20

将其打包在 Restlet Resource 类中的一行中:

Iterator it = new RestletFileUpload(new DiskFileItemFactory()).parseRequest(getRequest()).iterator();

然后,在您的项目循环中,您可以使用 isFormField() 方法测试它们是否是 fileItems。

测试 fileItem 是否是 formField...有意义吗? ;)
但它有效。

祝你好运。

to pack it on one line, in you Restlet Resource class :

Iterator it = new RestletFileUpload(new DiskFileItemFactory()).parseRequest(getRequest()).iterator();

Then in your loop through your items, you can test whether they are or not fileItems with the method: isFormField().

Testing if a fileItem is a formField... makes sens ? ;)
but it works.

Good luck.

可可 2024-07-30 12:16:20

回答我自己的问题,这在 1.2 版本中目前不可行

To answer my own question, this is not currently feasible in version 1.2

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文