在我的JSP应用程序中,我想将文件上传到目录并将一些文本和文件扩展名插入到数据库中,这两者都可以独立工作,即我可以将文本插入数据库,或者我可以将文本将文件放入目录但是当我想做两个方法=“post”时会将文件发送到目录但不插入数据,如果我使用method =“get”则相反的情况发生。
(适用EDIT)
POST和GET方法不允许一次发生两件事吗?
<form enctype="multipart/form-data" action="ReplyValidator.jsp" method="post">
<td><b>Choose the file To Upload:</b></td>
<td><input name="file" type="file"></td>
Post your reply:<br/>
<textarea rows="5" cols="50" name="topicpost" required="required"></textarea></br>
<input type="submit" value="Reply"/>
</form>
用于输入数据和上传文件的表单
<%@ page import="java.io.*"%>
<%
String saveFile = "";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile = "C:/temp/" + saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%>
<% } %>
<c:choose>
<c:when test="${empty param.topicpost}">
<%-- empty so go back to form --%>
<jsp:forward page="ViewPosts.jsp" />
</c:when>
<c:otherwise>
<c:set var="filename" value="<%=saveFile %>"/>
<%java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); %>
<sql:update>
INSERT INTO topic_posts (topic_name, post_message, posted_by, post_date, file_upload) values (?,?,?,?,?)
<sql:param value="${topicname}"/>
<sql:param value="${param.topicpost}"/>
<sql:param value="${user}"/>
<sql:param value="<%=df.format(new java.util.Date())%>"/>
<sql:param value="${filename}"/>
</sql:update>
<jsp:forward page="index.jsp"></jsp:forward>
</c:otherwise>
</c:choose>