我正在尝试通过jsp表单将图像上传到数据库。但是有一个错误,
java.lang.IllegalStateException:调用Request.getPart时不带 多部分配置。向servlet添加@MultipartConfig, 或web.xml的multipart-config元素
我的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>
根据{{3}},作为子元素,但是也会出现错误;
严重:部署应用程序[events_handeling]时发生异常: org.xml.sax.SAXParseException; lineNumber:12; columnNumber:23; 存档[web]中的部署描述符文件WEB-INF / web.xml。 cvc-complex-type.2.4.a:发现从元素“ multipart-config”开始的无效内容。
web.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>
应该如何解决?
答案 0 :(得分:0)
在JSP或HTML页面的标记内写入(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());
}
从此代码读取文件并保存到数据库中。