因此,在我的课堂上,我被责令将图像上传到数据库,并将其发布并显示在网站上,使用servlet或php时非常简单,但是我被要求仅使用JSP文件来完成。为此,我必须从用户那里获取图像并将其作为参数传递并获得参数的一部分,这不是问题。
当我尝试运行它并且服务器要求@multipartconfig注释时,问题就开始了。我找不到将其添加到jsp代码中的方法。
<%@page import="javax.servlet.annotation.MultipartConfig"%> <%@page import="java.sql.*"%> <%@page import="java.io.InputStream"%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <% request.setCharacterEncoding("UTF-8"); Part p = request.getPart("image"); InputStream inputStream = null; if (p != null) { inputStream = p.getInputStream(); } String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test42"; Class.forName(driver); Connection con = DriverManager.getConnection(url, "root", "1234"); String sqlString = "INSERT INTO test42.images items(idimages) values(" + inputStream + ");"; String msg = p.toString(); %>
<form method="post" action="mainPage.jsp" enctype="multipart/form-data"> choose file : <input type="file" name="image" /> <input type="submit" value="submit"> </form>
这是来自服务器的消息:
java.lang.IllegalStateException: Request.getPart is called without multipart configuration. Either add a @MultipartConfig to the servlet, or a multipart-config element to web.xml
我尝试将其添加到web.xml中,但没有成功。…该应用程序因构建错误而崩溃;我从这里得到了这个解决方案:http : //docs.oracle.com/javaee/6/tutorial/doc/gmhal.html
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" 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"> <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>
您需要有一个servlet和一个servlet-mapping标签。
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" 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"> <session-config> <session-timeout> 30 </session-timeout> </session-config> <servlet> <servlet-name>uploadfile</servlet-name> <jsp-file>/mainPage.jsp</jsp-file> <multipart-config> <location>/temp</location> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> <file-size-threshold>1048576</file-size-threshold> </multipart-config> </servlet> <servlet-mapping> <servlet-name>uploadfile</servlet-name> <url-pattern>/mainPage.jsp</url-pattern> </servlet-mapping </web-app>