这是我在 ASP 中所做的:
在表格上:
<form id="form1" runat="server">
...
<asp:Button ID="cmdGetFileToUpload" runat="server" Text="Send File" />
...
<asp:Panel id=divUploadFile Visible="False" ...>
<input id="inpUploadFile" runat="server" name="inpUploadFile" type="file" />
<asp:Button ID="cmdUploadFile" runat="server" Text="Upload File" />
</asp:Panel
...
</form>
在后面的代码中:
Protected Sub cmdGetFileToUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetFileToUpload.Click
'This shows the upload file panel when the user clicks the Send Files button
Me.divUploadFile.Visible = True
... hide other panels
End Sub
Protected Sub cmdUploadFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUploadFile.Click
Dim oFile As HttpPostedFile
Dim sFullPathName as String
Dim sFileName as String
oFile = Request.Files(0)
If oFile.FileName <> "" Then
sFullPathName = oFile.FileName
sFileName = sFullPathName.Substring(sFullPathName.LastIndexOf("\") + 1)
oFile.SaveAs(Server.MapPath(".\myFolder\") & sFileName)
End If
... do stuff with the file
End Sub
我已经下载了 commons-fileupload.jar 及其依赖项并将它们放在我的项目中。但是我不清楚代码应该放在哪里。我有一个类方法,我在回发后设置我的页面时调用,所以把它放在那里,但 servletfileupload.ismultipartcontent(request) 总是返回 false。文档说这通常是因为请求已经被处理。因此,我将代码移至表单顶部,如下所示:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="myClasses.myClass,
org.apache.commons.fileupload.*,
org.apache.commons.fileupload.servlet.*,
org.apache.commons.fileupload.disk.*,
org.apache.commons.fileupload.servlet.*,
java.io.*, java.util.*"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>MyPageTile</title>
<style>
... various styles
</style>
<script type="text/javascript">
... various scripts
</script>
</head>
<body style="background-color:tan;" onload="window.history.forward();" >
<%@ include file="subforms/my_banner.jsp" %>
<% if (session.getAttribute("user")==null) { response.sendRedirect("index.jsp"); }
else {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletContext servletContext = this.getServletConfig().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if ( ! item.isFormField() ) {
File uploadedFile = new File( "/uploads/" + session.getAttribute("user") + ".xlsm");
item.write(uploadedFile);
}
}
}
... other stuff then my form
<form id="AdminForm" enctype="multipart/form-data">
但是,servletfileupload.ismultipartcontent(request) 再次返回 false。
我究竟做错了什么?