多部分上传文件servlet [英] Multi part upload file servlet

查看:139
本文介绍了多部分上传文件servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何上传文件并获取表单的其他参数?我想在Java servlet中处理多个部分的请求。

解决方案

要浏览并选择要上传的文件,您需要一个< input type =file> 字段。正如 HTML规范所述,您需要使用 POST 方法,表单的enctype属性必须设置为 multipart / form-data

 < form action =uploadServletmethod =postenctype =multipart / form-data> 
< input type =filename =file/>
< input type =submit/>
< / form>

提交这样的表单后,表单数据可以以多部分格式在 HttpServletRequest的#的getInputStream()。为了测试(!)的目的,你可以使用下面的代码片段读取流:

  BufferedReader reader = new BufferedReader(new InputStreamReader .getInputStream())); 
for(String line;(line = reader.readLine())!= null;){
System.out.println(line);

$ / code>

然而,您需要解析流字节字节(而不是char字符)。在全新的 Servlet 3.0 API之前,标准的Servlet API没有提供任何内置工具来解析它们。常规表单字段也不是通常的 request.getParameter()方式,它们包含在多部分表单数据流中。

如果你还没有使用Servlet 3.0(只有不到2个旧的版本),那么你需要自己解析流。解析这样的数据流需要精确的背景知识,以了解多部分表单数据请求是如何指定和构造的。要创建一个完美的多部分分析器,你必须写很多代码。但幸运的是,已有多年的 Apache Commons FileUpload 已经证明了它的稳健性。仔细阅读用户指南常见问题解答查找代码示例,并学习如何使用它以达到最佳程度(以MSIE考虑!)。


How can I upload files and get other paramaters of a form? I want to handle multi part requests in Java servlet.

解决方案

To browse and select a file for upload you need a <input type="file"> field in the form. As stated in the HTML specification you need to use the POST method and the enctype attribute of the form has to be set to multipart/form-data.

<form action="uploadServlet" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>

After submitting such a form the form data is available in multipart format in the HttpServletRequest#getInputStream(). For testing(!) purposes you can read the stream using the following snippet:

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
for (String line; (line = reader.readLine()) != null;) {
    System.out.println(line);
}

You however need to parse the stream byte by byte (instead of char by char). Prior to the fresh new Servlet 3.0 API, the standard Servlet API didn't provide any builtin facilities to parse them. The normal form fields are also not available the usual request.getParameter() way, they are included in the multipart form data stream.

If you're not on Servlet 3.0 yet (which is only bit less than 2 monts old), then you need to parse the stream yourself. Parsing such a stream requires precise background knowledge of how multipart form data requests are specified and structured. To create a perfect multipart parser you'll have to write a lot of code. But fortunately there's the Apache Commons FileUpload which has proven its robustness with years. Carefully read both the User Guide and Frequently Asked Questions to find code examples and learn how to use it to an optimum degree (take MSIE into account!).

这篇关于多部分上传文件servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆