如何使用JSP/Servlet将文件上传到服务器?

如何使用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通用文件上传。我尝试了这个:

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)
637206 次浏览

导言

要浏览并选择要上传的文件,您需要在表单中使用超文本标记语言<input type="file">字段。如超文本标记语言规范中所述,您必须使用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时相比,一种不同的格式中的请求正文中的二进制多部分表单数据可用。

在Servlet 3.0(2009年12月)之前,Servlet API本身不支持multipart/form-data。它只支持application/x-www-form-urlencoded的默认表单enctype。当使用多部分表单数据时,request.getParameter()和组合都会返回null。这就是众所周知的Apache Commons文件上传出现的地方。

不要手动解析它!

理论上你可以基于ServletRequest#getInputStream()解析请求主体,但是这是一个精确而乏味的工作,需要你对RFC2388有精确的了解。你不应该尝试自己解析或者复制一些互联网上没有库的本地代码。很多在线资源在这方面都失败了,比如roseindia.net.另请参见上传pdf文件。你应该使用一个被数百万用户使用(并且隐式测试!)多年的真实库。这样的库已经证明了它的健壮性。

当您已经使用Servlet 3.0或更高版本时,请使用本机API

如果您至少使用Servlet 3.0(Tomcat 7、Jetty 9、JBoss AS 6、GlassFish 3等,它们自2010年以来就已经存在),那么您可以使用HttpServletRequest#getPart()提供的标准API来收集单独的多部分表单数据项(大多数Servlet 3.0实现实际上都使用Apache Commons FileUpload来实现这一点!)。此外,getParameter()以通常的方式提供普通表单字段。

首先用@MultipartConfig注释您的servlet,以便让它识别和支持multipart/form-data请求,从而让getPart()工作:

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
// ...
}

然后,实现其doPost()如下:

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)
}

注意Path#getFileName()。这是获取文件名的MSIE修复。此浏览器错误地沿着名称发送完整的文件路径,而不是仅发送文件名。

如果您想通过multiple="true"上传多个文件,

<input type="file" name="files" multiple="true" />

或者用多输入的老式方法,

<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
...

然后你可以收集它们如下(不幸的是没有request.getParts("files")这样的方法):

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)
}
}

当您还没有使用Servlet 3.1时,手动获取提交的文件名

请注意,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

如果你还没有使用Servlet 3.0(是时候升级了吗?它已经发布了十多年了!),通常的做法是使用Apache Commons文件上传来解析多部分表单数据请求。它有一个很好的用户指南FAQ(仔细检查两者)。还有O'Reilly(“cos”)MultipartRequest,但它有一些(小)错误,多年来不再积极维护。我不建议使用它。Apache Commons FileUpload仍在积极维护,目前非常成熟。

为了使用Apache Commons FileUpload,您需要在webapp的/WEB-INF/lib中至少包含以下文件:

您最初的尝试失败很可能是因为您忘记了公共IO。

以下是一个启动示例,当使用Apache Commons FileUpload时,UploadServletdoPost()可能是什么样子:

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);
}


// ...
}

不要事先对同一个请求调用getParameter()getParameterMap()getParameterValues()getInputStream()getReader()等。否则servlet容器将读取并解析请求正文,因此Apache Commons FileUpload将获得一个空的请求正文。另请参阅a. o.ServletFileUpload#parseRequest(请求)返回一个空列表

注意FilenameUtils#getName()。这是获取文件名的MSIE修复。此浏览器错误地沿着名称发送完整的文件路径,而不是仅发送文件名。

或者,您也可以将这一切包装在Filter中,该Filter自动解析所有内容并将其放回请求的参数映射中,以便您可以继续以通常的方式使用request.getParameter()并通过request.getAttribute()检索上传的文件。你可以在这篇博客文章中找到一个例子

解决方法GlassFish 3buggetParameter()仍返回null

请注意,早于3.1.2的Glassfish版本具有一个bug,其中getParameter()仍然返回null。如果您的目标是这样的容器并且无法升级它,那么您需要使用此实用方法从getPart()中提取值:

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">
    

保存上传的文件(不要使用getRealPath()part.write()!)

有关正确将获得的InputStream(如上面代码片段所示的fileContent变量)保存到磁盘或数据库的详细信息,请参阅以下答案:

上传文件

有关正确地将保存的文件从磁盘或数据库服务回客户端的详细信息,请参阅以下答案:

Ajaxi化形式

前往以下答案如何使用Ajax(和jQuery)上传。请注意,收集表单数据的servlet代码不需要为此而改变!只有响应方式可能会改变,但这是相当琐碎的(即,不是转发到JSP,只需打印一些JSON或XML甚至纯文本,具体取决于负责Ajax调用的脚本期望的内容)。


希望这一切都有帮助:)

您需要将common-io.1.4.jar文件包含在lib目录中,或者如果您在任何编辑器中工作,例如NetBeans,那么您需要转到项目属性并只需添加JAR文件即可完成。

要获取common.io.jar文件,只需谷歌搜索它,或者只需转到ApacheTomcat网站,您可以选择免费下载此文件。但请记住一件事:如果您是Windows用户,请下载二进制ZIP文件。

我正在使用超文本标记语言的通用Servlet,无论它是否有附件。

这个Servlet返回一个TreeMap,其中键是JSP名称参数,值是用户输入,并将所有附件保存在固定目录中,然后重命名您选择的目录。这里连接数是我们具有连接对象的自定义接口。

public class ServletCommonfunctions extends HttpServlet implements
Connections {


private static final long serialVersionUID = 1L;


public ServletCommonfunctions() {}


protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {}


public SortedMap<String, String> savefilesindirectory(
HttpServletRequest request, HttpServletResponse response)
throws IOException {


// Map<String, String> key_values = Collections.synchronizedMap(new
// TreeMap<String, String>());
SortedMap<String, String> key_values = new TreeMap<String, String>();
String dist = null, fact = null;
PrintWriter out = response.getWriter();
File file;
String filePath = "E:\\FSPATH1\\2KL06CS048\\";
System.out.println("Directory Created   ????????????"
+ new File(filePath).mkdir());
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;


// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// Maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File(filePath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
@SuppressWarnings("unchecked")
List<FileItem> fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator<FileItem> i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fileName = fi.getName();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
} else {
key_values.put(fi.getFieldName(), fi.getString());
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
return key_values;
}
}

如果您将Geronimo与其嵌入式Tomcat一起使用,则会出现此问题的另一个来源。在这种情况下,经过多次测试共享资源IO和Commons-fileupload的迭代后,问题源于处理Commons-xxx JAR文件的父类加载器。必须防止这种情况。崩溃总是发生在:

fileItems = uploader.parseRequest(request);

请注意,fileItems的List类型已随着当前版本的Commons-fileupload而更改为专门的List<FileItem>,而不是以前的通用版本List

我在我的Eclipse项目中添加了Commons-fileupload和Commons IO的源代码来跟踪实际错误,并最终获得了一些见解。首先,抛出的异常类型为Throwable,而不是声明的FileIOException,甚至也不是Exception(这些不会被捕获)。其次,错误消息令人困惑,因为它声明未找到类,因为axis2找不到Commons-io。Axis2根本没有在我的项目中使用,但作为标准安装的一部分,它作为Geronimo存储库子目录中的文件夹存在。

最后,我找到了一个地方,它提出了一个成功解决我的问题的工作解决方案。您必须在部署方案中从父加载程序中隐藏JAR文件。这被放入geronimo-web.xml文件中,我的完整文件如下所示。

http://osdir.com/ml/user-geronimo-apache/2011-03/msg00026.html粘贴:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<web:web-app xmlns:app="http://geronimo.apache.org/xml/ns/j2ee/application-2.0" xmlns:client="http://geronimo.apache.org/xml/ns/j2ee/application-client-2.0" xmlns:conn="http://geronimo.apache.org/xml/ns/j2ee/connector-1.2" xmlns:dep="http://geronimo.apache.org/xml/ns/deployment-1.2" xmlns:ejb="http://openejb.apache.org/xml/ns/openejb-jar-2.2" xmlns:log="http://geronimo.apache.org/xml/ns/loginconfig-2.0" xmlns:name="http://geronimo.apache.org/xml/ns/naming-1.2" xmlns:pers="http://java.sun.com/xml/ns/persistence" xmlns:pkgen="http://openejb.apache.org/xml/ns/pkgen-2.1" xmlns:sec="http://geronimo.apache.org/xml/ns/security-2.0" xmlns:web="http://geronimo.apache.org/xml/ns/j2ee/web-2.0.1">
<dep:environment>
<dep:moduleId>
<dep:groupId>DataStar</dep:groupId>
<dep:artifactId>DataStar</dep:artifactId>
<dep:version>1.0</dep:version>
<dep:type>car</dep:type>
</dep:moduleId>


<!-- Don't load commons-io or fileupload from parent classloaders -->
<dep:hidden-classes>
<dep:filter>org.apache.commons.io</dep:filter>
<dep:filter>org.apache.commons.fileupload</dep:filter>
</dep:hidden-classes>
<dep:inverse-classloading/>


</dep:environment>
<web:context-root>/DataStar</web:context-root>
</web:web-app>

为文件发送多个文件,我们必须使用enctype="multipart/form-data"

要发送多个文件,请在输入标签中使用multiple="multiple"

<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileattachments"  multiple="multiple"/>
<input type="submit" />
</form>

在Tomcat 6或Tomcat 7中没有组件或外部库

web.xml文件中启用上传:

手动安装PHP,Tomcat和Httpd休息室

<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>

如你所见

<multipart-config>
<max-file-size>3145728</max-file-size>
<max-request-size>5242880</max-request-size>
</multipart-config>

使用JSP上传文件。文件:

在超文本标记语言文件中

<form method="post" enctype="multipart/form-data" name="Form" >


<input type="file" name="fFoto" id="fFoto" value="" /></td>
<input type="file" name="fResumen" id="fResumen" value=""/>

在JSP文件中Servlet

InputStream isFoto = request.getPart("fFoto").getInputStream();
InputStream isResu = request.getPart("fResumen").getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[8192];
int qt = 0;
while ((qt = isResu.read(buf)) != -1) {
baos.write(buf, 0, qt);
}
String sResumen = baos.toString();

根据servlet要求编辑代码,例如最大文件大小请求大小最大值和您可以设置的其他选项…

您可以使用JSP上传文件 /servlet.

<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>

另一方面,在服务器端,使用以下代码。

package com.abc..servlet;


import java.io.File;
---------
--------




/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;


public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub


PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path") != null ? httpSession.getAttribute("path").toString() : "" ;


String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item = null;




boolean isMultipart = ServletFileUpload.isMultipartContent(request);


if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();


if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* Start of code fro privilege */


File uploadedFile = new File(path + Filename);  // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}


} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

用途:

DiskFileUpload upload = new DiskFileUpload();

从这个对象中,您必须获取文件项和字段,然后您可以像下面这样存储到服务器中:

String loc = "./webapps/prjct name/server folder/" + contentid + extension;
File uploadFile = new File(loc);
item.write(uploadFile);

下面是一个使用apache Commons-fileupload的示例:

// apache commons-fileupload to handle file upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(DataSources.TORRENTS_DIR()));
ServletFileUpload fileUpload = new ServletFileUpload(factory);


List<FileItem> items = fileUpload.parseRequest(req.raw());
FileItem item = items.stream()
.filter(e ->
"the_upload_name".equals(e.getFieldName()))
.findFirst().get();
String fileName = item.getName();


item.write(new File(dir, fileName));
log.info(fileName);

如果你碰巧使用Spring mvc,这是如何(我把这个留在这里,以防有人发现它很有用):

使用enctype属性设置为“multipart/form-data”的表单(与BalusC的回答相同):

<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload"/>
</form>

在控制器中,将请求参数file映射到MultipartFile类型,如下所示:

@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
}
}

您可以使用MultipartFilegetOriginalFilename()getSize()获取文件名和大小。

我已经用Spring版本4.1.1.RELEASE测试过了。

超文本标记语言页

<html>
<head>
<title>File Uploading Form</title>
</head>


<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
enctype="multipart/form-data">


<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

Servlet文件

// Import required java libraries
import java.io.*;
import java.util.*;


import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;


public class UploadServlet extends HttpServlet {


private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file;


public void init() {
// Get the file location where it would be stored.
filePath =
getServletContext().getInitParameter("file-upload");
}


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {


// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
if (!isMultipart) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}


DiskFileItemFactory factory = new DiskFileItemFactory();
// Maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));


// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);


try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);


// Process the uploaded file items
Iterator i = fileItems.iterator();


out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (i.hasNext())
{
FileItem fi = (FileItem)i.next();
if (!fi.isFormField())
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();


// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\")));
}
else {
file = new File(filePath +
fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}
catch(Exception ex) {
System.out.println(ex);
}
}


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {


throw new ServletException("GET method used with " +
getClass().getName() + ": POST method required.");
}
}

文件web.xml

编译上面的servlet UploadServlet并在web.xml文件中创建所需的条目,如下所示。

<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>UploadServlet</servlet-class>
</servlet>


<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

对于Spring MVC

我设法有一个更简单的版本,用于获取表单输入,数据和图像。

<form action="/handleform" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="file" />
<input type="submit" />
</form>

控制器来处理

@Controller
public class FormController {
@RequestMapping(value="/handleform",method= RequestMethod.POST)
ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
throws ServletException, IOException {


System.out.println(name);
System.out.println(age);
if(!file.isEmpty()){
byte[] bytes = file.getBytes();
String filename = file.getOriginalFilename();
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
stream.write(bytes);
stream.flush();
stream.close();
}
return new ModelAndView("index");
}
}

我能想到的文件和输入控件的最简单方法,没有十亿个库:

  <%
if (request.getContentType() == null)
return;
// For input type=text controls
String v_Text =
(new BufferedReader(new InputStreamReader(request.getPart("Text1").getInputStream()))).readLine();


// For input type=file controls
InputStream inStr = request.getPart("File1").getInputStream();
char charArray[] = new char[inStr.available()];
new InputStreamReader(inStr).read(charArray);
String contents = new String(charArray);
%>

您首先必须将表单的enctype属性设置为“multipart/form-data”

如下所示。

<form action="Controller" method="post" enctype="multipart/form-data">
<label class="file-upload"> Click here to upload an Image </label>
<input type="file" name="file" id="file" required>
</form>

然后,在Servlet“Controller”中添加多部分注释以指示在servlet中处理多部分数据。

执行此操作后,检索通过表单发送的部分,然后检索提交文件的文件名(带路径)。使用它在所需路径中创建一个新文件,并将文件的各部分写入新创建的文件以重新创建文件。

如下图所示:

@MultipartConfig


public class Controller extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
insertImage(request, response);
}


private void addProduct(HttpServletRequest request, HttpServletResponse response) {
Part filePart = request.getPart("file");
String imageName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();


String imageSavePath = "specify image path to save image"; //path to save image
FileOutputStream outputStream = null;
InputStream fileContent = null;


try {
outputStream = new FileOutputStream(new File(imageSavePath + File.separator + imageName));
// Creating a new file with file path and the file name
fileContent = filePart.getInputStream();
// Getting the input stream
int readBytes = 0;
byte[] readArray = new byte[1024];
// Initializing a byte array with size 1024


while ((readBytes = fileContent.read(readArray)) != -1) {
outputStream.write(readArray, 0, readBytes);
} // This loop will write the contents of the byte array unitl the end to the output stream
} catch (Exception ex) {
System.out.println("Error Writing File: " + ex);
} finally {
if (outputStream != null) {
outputStream.close();
// Closing the output stream
}
if (fileContent != null) {
fileContent.close();
// Closing the input stream
}
}
}
}