JSP
<form action="AddCategoryServlet" id="AddCategoryForm" target="_self" method="post">
<table>
<tr>
<td> <div align="center" class="group">
<input type="text" id="CName" name="texCname" required />
<span class="highlight"></span>
<span class="bar"></span>
<label id="CNamecheck">Category Name</label>
</div>
</tr>
<tr>
<td> <div align="center" class="group">
<input type="text" id="CDescript" name="texCdescript" required />
<span class="highlight"></span>
<span class="bar"></span>
<label id="CDescriptcheck">Category Description</label>
</div>
</tr>
<tr>
<td> <div align="center" class="group">
<input type="text" id="CImage" name="texCImage" required/>
<span class="highlight"></span>
<span class="bar"></span>
<label id="CImagecheck">File Path</label>
<input style="display:none;" type="file" id="file" name="file"/>
<input style="position:absolute;top:10px;left:315px;font-size:10px;" type="button" value="Choose Image" id="uploadbutton" class="myButton" />
</div>
</tr>
</table>
<input type="submit" value="Add Category" class="myButton" />
</form>单击“触发”时,选择“图像”按钮,使用jquery单击输入type=file的事件-:
$("#uploadbutton").click(function(){
$("#file").click();
});我将文件放入数据库的servlet是-:
try
{
String Name,Description=null;
Name=request.getParameter("texCname");
Description=request.getParameter("texCdescript");
InputStream inputStream= null;
Part filePart= null;
filePart= request.getPart("file");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection con= BaseDAO.getConnection();
PreparedStatement pst = con.prepareStatement("INSERT INTO CATEGORY(Category_Name, Image, Description) VALUES (?,?,?)");
pst.setString(1,Name);
pst.setBlob(2,inputStream);
pst.setString(3,Description);
pst.executeUpdate();
}
catch(ClassNotFoundException | SQLException e)
{
e.printStackTrace();
}我得到了“图像”列不能为空的错误。调试时,我发现变量filePart的值为null,即它没有从jsp接收带有name="file“的参数。有人能指出我哪里出了问题吗。
发布于 2015-06-13 21:15:14
不能一次以单一形式处理普通输入类型(如文本和输入类型文件),需要特殊的库来处理此类请求。
你需要在你的表单中写enctype="multipart/form-data",
<form action="AddCategoryServlet" id="AddCategoryForm" target="_self" method="post" enctype="multipart/form-data" >
........
</form>但是,请注意,通过编写enctype="multipart/form-data",您将无法处理普通输入,即input type="text"
因此,如果您想要一种简单的方法,创建两个独立的表单,其中包含在发送图像时包含enctype="multipart/form-data",另一个就像您在问题中指定的那样,其中只包含文本数据。
https://stackoverflow.com/questions/30823428
复制相似问题