J2ee 图像上传错误:java.lang.IllegalStateException



>我正在尝试通过jsp表单将图像上传到数据库。但是有一个错误,因为,

java.lang.IllegalStateException: Request.getPart 被调用时没有 多部分配置。要么向 servlet 添加一个@MultipartConfig, 还是 Web 的多部分配置元素.xml

我的servlet代码;

/* image */
Part filePart = request.getPart("eImage"); //here is the error
InputStream inputStream = null;
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}

但是当我补充说,

<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>

作为子元素,根据 https://docs.oracle.com/javaee/7/tutorial/servlets011.htm,但也会出现错误,如;

严重:部署应用程序时出现异常 [events_handeling]: org.xml.sax.SAXParseException;行号: 12;列数: 23; 部署描述符文件 WEB-INF/web.xml in archive [web]。 cvc-complex-type.2.4.a:发现以元素"multipart-config"开头的无效内容。

网络.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</web-app>

应该如何解决这个问题?

在 JSP 或 HTML Page 中写入 (enctype="multipart/form-data"( 标记。

<form name="form1" method="post" enctype="multipart/form-data" action="insertimage.jsp">
<input type="file" name="ImageFile" id="ImageFile" />
<input type="submit" name="submit" value="submit" />
</form>

用于从请求中读取文件的 Java 函数

try {
String ImageFile="", itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
}
catch (FileUploadException e) { 
e.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
if(name.equals("ImageFile")) {
ImageFile=value;
}
}
else {
try {
itemName = item.getName();  
File savedFile = new File("config.getServletContext().getRealPath("/")+"Example\image-folder\"+itemName);
item.write(savedFile);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
catch (Exception e) {
out.println(e.getMessage());
}

从此代码读取文件并保存到数据库中。

相关内容

最新更新