php小编柚子为您介绍java中关于如何使用jsp/servlet将文件上传到服务器的方法。在web开发中,文件上传是一个常见需求,通过jsp/servlet可以实现简单且高效的文件上传功能。接下来,我们将详细介绍如何通过java代码实现文件上传至服务器的步骤,让您快速掌握这一技能,提升您的开发能力。
如何使用 jsp/servlet 将文件上传到服务器?
我尝试过这个:
<form action="upload" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
但是,我只获取文件名,而不获取文件内容。当我将 enctype="multipart/form-data" 添加到 <form> 时,request.getparameter() 返回 null。
在研究过程中,我偶然发现了 apache common fileupload。我试过这个:
fileitemfactory factory = new diskfileitemfactory(); servletfileupload upload = new servletfileupload(factory); list items = upload.parserequest(request); // this line is where it died.
不幸的是,servlet 抛出了一个异常,但没有明确的消息和原因。这是堆栈跟踪:
SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:637)
要浏览并选择要上传的文件,您需要在表单中添加 html <input type="file"> 字段。如 HTML specification 中所述,您必须使用 post 方法,并且表单的 enctype 属性必须设置为 "multipart/form-data"。
<form action="upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
提交此类表单后,与未设置 enctype 时相比,二进制多部分表单数据在 a different format 中的请求正文中可用。
在 servlet 3.0(2009 年 12 月)之前,servlet api 本身并不支持 multipart/form-data。它仅支持默认形式 enctype application/x-www-form-urlencoded。当使用多部分表单数据时,request.getparameter() 和 consorts 都将返回 null。这就是众所周知的 Apache Commons FileUpload 出现的地方。
理论上你可以根据ServletRequest#getInputStream()自己解析请求体。然而,这是一项精确而乏味的工作,需要对RFC2388有精确的了解。你不应该尝试自己这样做或复制粘贴一些自制的无库文件在互联网上其他地方找到的代码。许多在线资源在这方面都失败了,例如roseindia.net。另请参阅 uploading of pdf file。您应该使用真实的库,该库已被数百万用户使用(并隐式测试!)多年。这样的库已经证明了它的稳健性。
如果您至少使用 servlet 3.0(tomcat 7、jetty 9、jboss as 6、glassfish 3 等,它们自 2010 年以来就已经存在),那么您可以使用 HttpServletRequest#getPart() 提供的标准 api 来收集单独的多部分表单数据项(大多数 servlet 3.0 实现实际上都在幕后使用 apache commons fileupload!)。此外,正常形式字段可以通过 ServletRequest#getInputStream() 以通常的方式获得。
首先用 @MultipartConfig 注释您的 servlet,以便让它识别并支持 HttpServletRequest#getPart() 请求,从而使 getparameter() 正常工作:
@webservlet("/upload")
@multipartconfig
public class uploadservlet extends httpservlet {
// ...
}然后,按如下方式实现其 @MultipartConfig:
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
string description = request.getparameter("description"); // retrieves <input type="text" name="description">
part filepart = request.getpart("file"); // retrieves <input type="file" name="file">
string filename = paths.get(filepart.getsubmittedfilename()).getfilename().tostring(); // msie fix.
inputstream filecontent = filepart.getinputstream();
// ... (do your job here)
}
注意 multipart/form-data。这是有关获取文件名的 msie 修复。此浏览器错误地发送完整文件路径和名称,而不仅仅是文件名。
如果您想通过 getpart() 上传多个文件,
<input type="file" name="files" multiple="true" />
或者使用多个输入的老式方式,
<input type="file" name="files" /> <input type="file" name="files" /> <input type="file" name="files" /> ...
然后你可以按如下方式收集它们(不幸的是没有像 dopost() 这样的方法):
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
// ...
list<part> fileparts = request.getparts().stream().filter(part -> "files".equals(part.getname()) && part.getsize() > 0).collect(collectors.tolist()); // retrieves <input type="file" name="files" multiple="true">
for (part filepart : fileparts) {
string filename = paths.get(filepart.getsubmittedfilename()).getfilename().tostring(); // msie fix.
inputstream filecontent = filepart.getinputstream();
// ... (do your job here)
}
}请注意,Part#getSubmittedFileName() 是在 servlet 3.1 中引入的(tomcat 8、jetty 9、wildfly 8、glassfish 4 等,它们自 2013 年以来就已存在)。如果您还没有使用 servlet 3.1(真的吗?),那么您需要一个额外的实用方法来获取提交的文件名。
private static string getsubmittedfilename(part part) {
for (string cd : part.getheader("content-disposition").split(";")) {
if (cd.trim().startswith("filename")) {
string filename = cd.substring(cd.indexof('=') + 1).trim().replace(""", "");
return filename.substring(filename.lastindexof('/') + 1).substring(filename.lastindexof('\') + 1); // msie fix.
}
}
return null;
}string filename = getsubmittedfilename(filepart);
请注意有关获取文件名的 msie 修复。此浏览器错误地发送完整文件路径和名称,而不仅仅是文件名。
如果您还没有使用 servlet 3.0(是不是该升级了?它已经十多年前发布了!),通常的做法是使用 Apache Commons FileUpload 来解析多部分表单数据请求。它有一个很好的a different format0和a different format1(仔细检查两者)。还有 o'reilly(“a different format2”)path#getfilename(),但它有一些(小)错误,并且多年来不再积极维护。我不建议使用它。 apache commons fileupload 仍在积极维护,目前非常成熟。
为了使用 apache commons fileupload,您的 web 应用程序的 multiple="true" 中至少需要有以下文件:
您最初的尝试失败很可能是因为您忘记了公共 io。
下面是一个启动示例,显示使用 apache commons fileupload 时 request.getparts("files") 的 Part#getSubmittedFileName() 的样子:
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
try {
list<fileitem> items = new servletfileupload(new diskfileitemfactory()).parserequest(request);
for (fileitem item : items) {
if (item.isformfield()) {
// process regular form field (input type="text|radio|checkbox|etc", select, etc).
string fieldname = item.getfieldname();
string fieldvalue = item.getstring();
// ... (do your job here)
} else {
// process form file field (input type="file").
string fieldname = item.getfieldname();
string filename = filenameutils.getname(item.getname());
inputstream filecontent = item.getinputstream();
// ... (do your job here)
}
}
} catch (fileuploadexception e) {
throw new servletexception("cannot parse multipart request.", e);
}
// ...
}
非常重要的是,您不要事先在同一请求上调用 multipartrequest、/web-inf/lib、commons-fileupload.jar、commons-io.jar、uploadservlet 等。否则,servlet 容器将读取并解析请求正文,因此 apache commons fileupload 将得到一个空请求正文。另请参见 a.o. a different format5。
注意 dopost()。这是有关获取文件名的 msie 修复。此浏览器错误地发送完整文件路径和名称,而不仅仅是文件名。
或者,您也可以将这一切包装在 getparameter() 中,它会自动解析所有内容并将内容放回请求的参数映射中,以便您可以继续以通常的方式使用 getparametermap() 并通过以下方式检索上传的文件getparametervalues()。 a different format6。
getinputstream() 错误的解决方法仍然返回 getreader()
请注意,早于 3.1.2 的 glassfish 版本有 a different format7,其中 filenameutils#getname() 仍返回 filter。如果您的目标是这样的容器并且无法升级它,那么您需要借助此实用程序方法从 request.getparameter() 中提取值:
private static string getvalue(part part) throws ioexception {
bufferedreader reader = new bufferedreader(new inputstreamreader(part.getinputstream(), "utf-8"));
stringbuilder value = new stringbuilder();
char[] buffer = new char[1024];
for (int length = 0; (length = reader.read(buffer)) > 0;) {
value.append(buffer, 0, length);
}
return value.tostring();
}string description = getvalue(request.getpart("description")); // retrieves <input type="text" name="description">request.getattribute() 或 getparameter()!)前往以下答案,详细了解如何将获得的 null (上述代码片段中所示的 getparameter() 变量)正确保存到磁盘或数据库:
请参阅以下答案,了解如何正确地将保存的文件从磁盘或数据库返回给客户端的详细信息:
前往以下答案,了解如何使用 ajax(和 jquery)上传。请注意,无需为此更改用于收集表单数据的 servlet 代码!只有您响应的方式可能会改变,但这相当简单(即,不转发到 jsp,只需打印一些 json 或 xml 甚至纯文本,具体取决于负责 ajax 调用的脚本所期望的内容)。
如果您碰巧使用 Apache Commons FileUpload8,请按以下方法操作(我将其留在这里,以防有人发现它有用):
使用 null 属性设置为“getpart() 映射到 getrealpath() 类型,如下所示:
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="upload"/>
</form>
您可以使用 part.write() 的 inputstream 和 filecontent 获取文件名和大小。
我已经使用 spring 版本 enctype 对此进行了测试。
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
// application logic
}
}以上就是如何使用 JSP/Servlet 将文件上传到服务器?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号