如何使用 JSP -Servlet 和 EJB 3.0 上传图像 [英] How to upload an image using JSP -Servlet and EJB 3.0
问题描述
我想使用 JSP Servlet 和 ejb 3.0 上传图片
I want to upload an Image using JSP Servlet and ejb 3.0
推荐答案
首先,要使用 JSP 选择要上传的文件,您至少需要一个 HTML <input type="file">
将显示文件浏览字段的元素.如 HTML 表单规范所述,您需要在父 <form>
元素中将请求方法设置为 POST
并将请求编码设置为 multipart/form-data
.
To start, to select a file for upload using JSP you need at least a HTML <input type="file">
element which will display a file browse field. As stated in the HTML forms spec you need to set the request method to POST
and the request encoding to multipart/form-data
in the parent <form>
element.
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
因为 Servlet 3.0 (我不认为你正在使用它,因为 EJB 3.0 是 Java EE 5.0 的一部分,而 Java EE 5.0 又只包含 Servlet 2.5),你不会在请求中看到任何内容参数图.request.getParameter("file")
将返回 null
.
Because the aforementioned request encoding isn't by default supported by the Servlet API before Servlet 3.0 (which I don't think you're using because EJB 3.0 is part of Java EE 5.0 which in turn contains Servlet 2.5 only), you won't see anything in the request parameter map. The request.getParameter("file")
would return null
.
要在servlet中检索上传的文件和其他请求参数,您需要自己解析HttpServletRequest
的InputStream
.幸运的是,有一个常用的 API 可以让您摆脱繁琐的工作:Apache Commons FileUpload.
To retrieve the uploaded file and the other request parameters in a servlet, you need to parse the InputStream
of the HttpServletRequest
yourself. Fortunately there's a commonly used API which can take the tedious work from your hands: Apache Commons FileUpload.
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// <input type="file">
System.out.println("Field name: " + item.getFieldName());
System.out.println("File name: " + item.getName());
System.out.println("File size: " + item.getSize());
System.out.println("File type: " + item.getContentType());
} else {
// <input type="text|submit|hidden|password|button">, <select>, <textarea>, <button>
System.out.println("Field name: " + item.getFieldName());
System.out.println("Field value: " + item.getString());
}
}
基本上你只需要从 FileItem
对象中获取 InputStream
并使用通常的
Basically you just need to get the InputStream
from the FileItem
object and write it to any OutputStream
to your taste using the usual Java IO way.
InputStream content = item.getInputStream();
或者你也可以直接写:
item.write(new File("/uploads/filename.ext"));
在他们的主页上,您可以在 中找到许多代码示例和重要提示和技巧用户指南和常见问题 部分.仔细阅读它们.
At their homepage you can find lot of code examples and important tips&tricks in the User Guide and Frequently Asked Questions sections. Read them carefully.
这篇关于如何使用 JSP -Servlet 和 EJB 3.0 上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!