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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2422468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:24:52  来源:igfitidea点击:

How to upload files to server using JSP/Servlet?

javajspjakarta-eeservletsfile-upload

提问by Thang Pham

How can I upload files to server using JSP/Servlet? I tried this:

如何使用 JSP/Servlet 将文件上传到服务器?我试过这个:

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

However, I only get the file name, not the file content. When I add enctype="multipart/form-data"to the <form>, then request.getParameter()returns null.

但是,我只得到文件名,而不是文件内容。当我添加 enctype="multipart/form-data"<form>,然后request.getParameter()返回null

During research I stumbled upon Apache Common FileUpload. I tried this:

在研究期间,我偶然发现了Apache Common FileUpload。我试过这个:

FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request); // This line is where it died.

Unfortunately, the servlet threw an exception without a clear message and cause. Here is the stacktrace:

不幸的是,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)

采纳答案by BalusC

Introduction

介绍

To browse and select a file for upload you need a HTML <input type="file">field in the form. As stated in the HTML specificationyou have to use the POSTmethod and the enctypeattribute of the form has to be set to "multipart/form-data".

要浏览并选择要上传的文件,您需要<input type="file">在表单中添加一个 HTML字段。正如HTML 规范中所述,您必须使用该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>

After submitting such a form, the binary multipart form data is available in the request body in a different formatthan when the enctypeisn't set.

提交这样的表单后,二进制多部分表单数据以与未设置时不同的格式出现在请求正文中enctype

Before Servlet 3.0, the Servlet API didn't natively support multipart/form-data. It supports only the default form enctype of application/x-www-form-urlencoded. The request.getParameter()and consorts would all return nullwhen using multipart form data. This is where the well known Apache Commons FileUploadcame into the picture.

在 Servlet 3.0 之前,Servlet API 本身并不支持multipart/form-data. 它仅支持application/x-www-form-urlencoded. 使用多部分表单数据时,request.getParameter()和配偶都会返回null。这就是著名的Apache Commons FileUpload出现的地方。

Don't manually parse it!

不要手动解析它!

You can in theory parse the request body yourself based on ServletRequest#getInputStream(). However, this is a precise and tedious work which requires precise knowledge of RFC2388. You shouldn't try to do this on your own or copypaste some homegrown library-less code found elsewhere on the Internet. Many online sources have failed hard in this, such as roseindia.net. See also uploading of pdf file. You should rather use a real library which is used (and implicitly tested!) by millions of users for years. Such a library has proven its robustness.

理论上,您可以基于ServletRequest#getInputStream(). 然而,这是一项精确而繁琐的工作,需要精确了解RFC2388。你不应该尝试自己做这件事或复制粘贴一些在互联网上其他地方找到的本土无库代码。许多在线资源在这方面都失败了,例如roseindia.net。另请参阅上传 pdf 文件。您应该使用一个真实的库,该库多年来被数百万用户使用(并进行了隐式测试!)。这样的库已经证明了它的健壮性。

When you're already on Servlet 3.0 or newer, use native API

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

If you're using at least Servlet 3.0 (Tomcat 7, Jetty 9, JBoss AS 6, GlassFish 3, etc), then you can just use standard API provided HttpServletRequest#getPart()to collect the individual multipart form data items (most Servlet 3.0 implementations actually use Apache Commons FileUpload under the covers for this!). Also, normal form fields are available by getParameter()the usual way.

如果您至少使用 Servlet 3.0(Tomcat 7、Jetty 9、JBoss AS 6、GlassFish 3 等),那么您只需使用提供的标准 APIHttpServletRequest#getPart()来收集各个多部分表单数据项(大多数 Servlet 3.0 实现实际上使用 Apache为此,Commons FileUpload 在幕后!)。此外,普通表单字段可以通过getParameter()通常的方式使用。

First annotate your servlet with @MultipartConfigin order to let it recognize and support multipart/form-datarequests and thus get getPart()to work:

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

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

Then, implement its doPost()as follows:

然后,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)
}

Note the Path#getFileName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

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

In case you have a <input type="file" name="file" multiple="true" />for multi-file upload, collect them as below (unfortunately there is no such method as request.getParts("file")):

如果您有一个<input type="file" name="file" multiple="true" />多文件上传,请按如下方式收集它们(遗憾的是没有这样的方法request.getParts("file")):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // ...
    List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName()) && part.getSize() > 0).collect(Collectors.toList()); // Retrieves <input type="file" name="file" multiple="true">

    for (Part filePart : fileParts) {
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        // ... (do your job here)
    }
}

When you're not on Servlet 3.1 yet, manually get submitted file name

当您尚未使用 Servlet 3.1 时,请手动获取提交的文件名

Note that Part#getSubmittedFileName()was introduced in Servlet 3.1 (Tomcat 8, Jetty 9, WildFly 8, GlassFish 4, etc). If you're not on Servlet 3.1 yet, then you need an additional utility method to obtain the submitted file name.

请注意,它Part#getSubmittedFileName()是在 Servlet 3.1(Tomcat 8、Jetty 9、WildFly 8、GlassFish 4 等)中引入的。如果您还没有使用 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);

Note the MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

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

When you're not on Servlet 3.0 yet, use Apache Commons FileUpload

如果您还没有使用 Servlet 3.0,请使用 Apache Commons FileUpload

If you're not on Servlet 3.0 yet (isn't it about time to upgrade?), the common practice is to make use of Apache Commons FileUploadto parse the multpart form data requests. It has an excellent User Guideand FAQ(carefully go through both). There's also the O'Reilly ("cos") MultipartRequest, but it has some (minor) bugs and isn't actively maintained anymore for years. I wouldn't recommend using it. Apache Commons FileUpload is still actively maintained and currently very mature.

如果您还没有使用 Servlet 3.0(不是该升级了吗?),通常的做法是使用Apache Commons FileUpload来解析多部分表单数据请求。它有一个很好的用户指南常见问题解答(仔细阅读两者)。还有 O'Reilly (" cos") MultipartRequest,但它有一些(小)错误,并且多年来不再积极维护。我不建议使用它。Apache Commons FileUpload 仍在积极维护中,目前非常成熟。

In order to use Apache Commons FileUpload, you need to have at least the following files in your webapp's /WEB-INF/lib:

为了使用 Apache Commons FileUpload,你的 webapp 中至少需要有以下文件/WEB-INF/lib

Your initial attempt failed most likely because you forgot the commons IO.

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

Here's a kickoff example how the doPost()of your UploadServletmay look like when using Apache Commons FileUpload:

这里有一个例子开球怎么doPost()你的UploadServlet可以看看使用Apache通用FileUpload时,如:

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

    // ...
}

It's very important that you don't call getParameter(), getParameterMap(), getParameterValues(), getInputStream(), getReader(), etc on the same request beforehand. Otherwise the servlet container will read and parse the request body and thus Apache Commons FileUpload will get an empty request body. See also a.o. ServletFileUpload#parseRequest(request) returns an empty list.

这是非常重要的,你不叫getParameter()getParameterMap()getParameterValues()getInputStream()getReader()等上预先同样的要求。否则 servlet 容器将读取并解析请求正文,因此 Apache Commons FileUpload 将获得一个空的请求正文。另见 ao ServletFileUpload#parseRequest(request) 返回一个空列表

Note the FilenameUtils#getName(). This is a MSIE fix as to obtaining the file name. This browser incorrectly sends the full file path along the name instead of only the file name.

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

Alternatively you can also wrap this all in a Filterwhich parses it all automagically and put the stuff back in the parametermap of the request so that you can continue using request.getParameter()the usual way and retrieve the uploaded file by request.getAttribute(). You can find an example in this blog article.

或者,您也可以将所有这些都包装在 a 中Filter,它会自动解析所有内容并将这些内容放回请求的参数映射中,以便您可以继续使用request.getParameter()通常的方式并通过request.getAttribute(). 您可以在此博客文章中找到示例

Workaround for GlassFish3 bug of getParameter()still returning null

getParameter()仍然返回的GlassFish3 错误的解决方法null

Note that Glassfish versions older than 3.1.2 had a bugwherein the getParameter()still returns null. If you are targeting such a container and can't upgrade it, then you need to extract the value from getPart()with help of this utility method:

请注意,早于 3.1.2 的 Glassfish 版本有一个错误,其中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">

Saving uploaded file (don't use getRealPath()nor part.write()!)

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

Head to the following answers for detail on properly saving the obtained InputStream(the fileContentvariable as shown in the above code snippets) to disk or database:

有关将获得的InputStreamfileContent如上述代码片段中所示的变量)正确保存到磁盘或数据库的详细信息,请前往以下答案:

Serving uploaded file

提供上传的文件

Head to the following answers for detail on properly serving the saved file from disk or database back to the client:

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

Ajaxifying the form

对表单进行 Ajax 化

Head to the following answers how to upload using Ajax (and jQuery). Do note that the servlet code to collect the form data does not need to be changed for this! Only the way how you respond may be changed, but this is rather trivial (i.e. instead of forwarding to JSP, just print some JSON or XML or even plain text depending on whatever the script responsible for the Ajax call is expecting).

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



Hope this all helps :)

希望这一切都有帮助:)

回答by Pranav

You need the common-io.1.4.jarfile to be included in your libdirectory, or if you're working in any editor, like NetBeans, then you need to go to project properties and just add the JAR file and you will be done.

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

To get the common.io.jarfile just google it or just go to the Apache Tomcatwebsite where you get the option for a free download of this file. But remember one thing: download the binary ZIP file if you're a Windows user.

要获取该common.io.jar文件,只需使用谷歌搜索或访问 Apache Tomcat网站,在那里您可以获得免费下载该文件的选项。但请记住一件事:如果您是 Windows 用户,请下载二进制 ZIP 文件。

回答by feel good and programming

I am Using common Servlet for everyHtml Form whether it has attachments or not. This Servlet returns a TreeMapwhere the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you

我正在为每个Html 表单使用通用 Servlet,无论它是否有附件。这个 Servlet 返回一个TreeMap,其中键是 jsp 名称参数和值是用户输入,并将所有附件保存在固定目录中,稍后您重命名您选择的目录。这里 Connections 是我们具有连接对象的自定义接口。我想这会帮助你

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

回答by Geoffrey Malafsky

Another source of this problem occurs if you are using Geronimo with its embedded Tomcat. In this case, after many iterations of testing commons-io and commons-fileupload, the problem arises from a parent classloader handling the commons-xxx jars. This has to be prevented. The crash always occurred at:

如果您使用 Geronimo 及其嵌入式 Tomcat,则会出现此问题的另一个来源。在这种情况下,经过多次测试 commons-io 和 commons-fileupload 后,问题出在处理 commons-xxx jar 的父类加载器。这是必须防止的。崩溃总是发生在:

fileItems = uploader.parseRequest(request);

Note that the List type of fileItems has changed with the current version of commons-fileupload to be specifically List<FileItem>as opposed to prior versions where it was generic List.

请注意,fileItems 的 List 类型已随着当前版本的 commons-fileupload 发生变化,与List<FileItem>以前版本的 generics不同List

I added the source code for commons-fileupload and commons-io into my Eclipse project to trace the actual error and finally got some insight. First, the exception thrown is of type Throwable not the stated FileIOException nor even Exception (these will not be trapped). Second, the error message is obfuscatory in that it stated class not found because axis2 could not find commons-io. Axis2 is not used in my project at all but exists as a folder in the Geronimo repository subdirectory as part of standard installation.

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

Finally, I found 1 place that posed a working solution which successfully solved my problem. You must hide the jars from parent loader in the deployment plan. This was put into geronimo-web.xml with my full file shown below.

最后,我找到了 1 个提出有效解决方案的地方,它成功地解决了我的问题。您必须在部署计划中对父加载程序隐藏 jar。这与我的完整文件一起放入 geronimo-web.xml 中,如下所示。

Pasted from <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>

回答by rohan kamat

Sending multiple file for file we have to use enctype="multipart/form-data"
and to send multiple file use multiple="multiple"in input tag

为我们必须使用的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>

回答by joseluisbz

Without component or external Library in Tomcat 6 o 7

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

Enabling Upload in the web.xmlfile:

web.xml文件中启用上传:

http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads.

http://joseluisbz.wordpress.com/2014/01/17/manually-installing-php-tomcat-and-httpd-lounge/#Enabling%20File%20Uploads

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

AS YOU CAN SEE:

如您所见

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

Uploading Files using JSP. Files:

使用 JSP 上传文件。文件:

In the html file

在 html 文件中

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

In the JSP Fileor Servlet

在 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();

Edit your code to servlet requirements, like max-file-size, max-request-sizeand other options that you can to set...

将您的代码编辑为 servlet 要求,例如max-file-sizemax-request-size和您可以设置的其他选项...

回答by Mitul Maheshwari

you can upload file using jsp /servlet.

您可以使用jsp /servlet 上传文件。

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

on the other hand server side. use following code.

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

     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 PRIVILEDGE*/

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

}

回答by Mahender Reddy Yasa

DiskFileUpload upload=new DiskFileUpload();

From this object you have to get file items and fields then yo can store into server like followed:

从这个对象你必须得到文件项和字段然后你可以存储到服务器中,如下所示:

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

回答by thouliha

Here's an example using apache commons-fileupload:

下面是一个使用 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);

回答by Amila

If you happen to use Spring MVC, this is how to: (I'm leaving this here in case someone find it useful).

如果您碰巧使用 Spring MVC,这就是如何:(我将把它留在这里以防有人觉得它有用)。

Use a form with enctypeattribute set to "multipart/form-data" (Same as BalusC's Answer)

使用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>

In your controller, map the request parameter fileto MultipartFiletype as follows:

在您的控制器中,将请求参数映射fileMultipartFile类型,如下所示:

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

You can get the filename and size using MultipartFile's getOriginalFilename()and getSize().

您可以使用MultipartFile'sgetOriginalFilename()和获取文件名和大小getSize()

I've tested this with Spring version 4.1.1.RELEASE.

我已经用 Spring 版本对此进行了测试4.1.1.RELEASE