很抱歉,我对jsp完全不熟悉。
如何检索上传的图像并使用jsp保存到文件?
答案 0 :(得分:9)
创建至少包含以下内容的JSP文件:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit">
</form>
转到Apache Commons FileUpload homepage,阅读 User Guide和Frequently Asked Questions部分。
下载以下库的二进制文件:
解压缩拉链并将JAR文件放在网络项目的/WEB-INF/lib
中。
创建一个至少包含以下内容的Servlet类:
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<FileItem> items = null;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form fields here the same way as request.getParameter().
// You can get parameter name by item.getFieldName();
// You can get parameter value by item.getString();
} else {
// Process uploaded fields here.
String filename = FilenameUtils.getName(item.getName()); // Get filename.
File file = new File("/path/to/uploads", filename); // Define destination file.
item.write(file); // Write to destination file.
}
}
// Show result page.
request.getRequestDispatcher("result.jsp").forward(request, response);
}
}
将weblet映射到web.xml中,如下所示:
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>mypackage.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
那应该是它。当您在JSP中提交表单时,它将调用与servlet的/upload
匹配的操作<url-pattern>
,然后servlet将在doPost()
方法中执行其任务。最后,这一切都相当简单。希望这会有所帮助。