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

时间:2021-01-27 21:19:10

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"添加到

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

12 个解决方案

#1


1033  

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 specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

要浏览并选择一个文件,你需要一个HTML 字段。正如HTML规范中所述,必须使用POST方法,表单的enctype属性必须设置为“多部分/表单数据”。

<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 format than when the enctype isn'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 null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

在Servlet 3.0之前,Servlet API并没有直接支持多部分/表单数据。它只支持应用程序/x-www-form-urlencode的默认表单。当使用多部分表单数据时,请求. getparameter()和consort都将返回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

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等),那么您就可以使用标准API提供HttpServletRequest#getPart()来收集单个的多部分表单数据项(大多数Servlet 3.0实现实际上都使用Apache Commons FileUpload来实现这一点!)另外,正常的表单字段可以通过getParameter()方法获得。

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

首先使用@MultipartConfig来注释您的servlet,以便让它识别和支持多部分/表单数据请求,从而获得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.

注意路径# 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")):

如果你有一个进行多文件上传,请将它们收集如下(不幸的是,没有这样的方法,如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())).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

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.

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

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 FileUpload to parse the multpart form data requests. It has an excellent User Guide and 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来解析multpart表单数据请求。它有一个优秀的用户指南和FAQ(仔细地浏览这两个)。还有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.

你最初的尝试失败了很可能是因为你忘记了commons IO。

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

这里有一个kickoff的例子,说明UploadServlet的doPost()在使用Apache Commons 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将获得一个空请求体。还可以看到a.o. 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 Filter which 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.

或者,您也可以将其打包在一个过滤器中,它可以自动地解析它,并将这些东西放到请求的参数映射中,这样您就可以继续使用request. getparameter()方法,并通过request. getattribute()来检索已上传的文件。你可以在这篇博客文章中找到一个例子。

Workaround for GlassFish3 bug of getParameter() still returning null

Note that Glassfish versions older than 3.1.2 had a bug wherein 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()!)

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

对于正确保存获得的InputStream(如上面的代码片段所示的fileContent变量)到磁盘或数据库的详细信息,请访问下面的答案:

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

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

希望这一切都有帮助:)

#2


22  

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 enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)

使用带有enctype属性的表单,设置为“多部分/表单数据”(与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 file to MultipartFile type as follows:

在您的控制器中,将请求参数文件映射到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
    }
}

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

您可以使用MultipartFile的getOriginalFilename()和getSize()获得文件名和大小。

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

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

#3


11  

You need the common-io.1.4.jar file to be included in your lib directory, 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.jar file just google it or just go to the Apache Tomcat website 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文件。

#4


8  

I am Using common Servlet for every Html Form whether it has attachments or not. This Servlet returns a TreeMap where 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名称参数,值是用户输入,并保存在固定目录中的所有附件,稍后您将重新命名您选择的目录。这里的连接是我们的自定义接口具有连接对象。我想这对你有帮助。

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

#5


6  

Without component or external Library in Tomcat 6 o 7

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

Enabling Upload in the web.xml file:

启用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/启用% 20文件% 20上传。

<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 File or 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-size and other options that you can to set...

编辑您的代码到servlet需求,如max文件大小,max-request-size和其他您可以设置的选项…

#6


6  

For Spring MVC I have been trying for hours to do this and managed to have a simpler version that worked for taking form input both data and image.

对于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 to handle

控制器处理

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

Hope it helps :)

希望它能帮助:)

#7


5  

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,则会出现另一个问题。在这种情况下,经过多次测试common -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的列表类型已经随着common -fileupload的当前版本进行了更改,以具体列出 ,而不是以前的版本。

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.

我将common -fileupload和common- io的源代码添加到Eclipse项目中,以跟踪实际的错误,并最终获得了一些见解。首先,抛出的异常是类型转换,而不是声明的FileIOException,也不是异常(这些将不会被捕获)。其次,错误消息是模糊的,因为它声明的类没有找到,因为axis2无法找到common -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.

最后,我找到了一个工作解决方案,成功地解决了我的问题。在部署计划中,必须将jar隐藏在父加载器中。这被放进了geronimoweb。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>

#8


0  

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

#9


-1  

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

}

#10


-1  

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

#11


-2  

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",并在输入标签中发送多个文件使用多个="多个"。

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

#12


-2  

HTML PAGE

HTML页面

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

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

web . xml

Compile above servlet UploadServlet and create required entry in web.xml file as follows.

编译上面的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>

#1


1033  

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 specification you have to use the POST method and the enctype attribute of the form has to be set to "multipart/form-data".

要浏览并选择一个文件,你需要一个HTML 字段。正如HTML规范中所述,必须使用POST方法,表单的enctype属性必须设置为“多部分/表单数据”。

<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 format than when the enctype isn'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 null when using multipart form data. This is where the well known Apache Commons FileUpload came into the picture.

在Servlet 3.0之前,Servlet API并没有直接支持多部分/表单数据。它只支持应用程序/x-www-form-urlencode的默认表单。当使用多部分表单数据时,请求. getparameter()和consort都将返回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

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等),那么您就可以使用标准API提供HttpServletRequest#getPart()来收集单个的多部分表单数据项(大多数Servlet 3.0实现实际上都使用Apache Commons FileUpload来实现这一点!)另外,正常的表单字段可以通过getParameter()方法获得。

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

首先使用@MultipartConfig来注释您的servlet,以便让它识别和支持多部分/表单数据请求,从而获得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.

注意路径# 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")):

如果你有一个进行多文件上传,请将它们收集如下(不幸的是,没有这样的方法,如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())).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

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.

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

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 FileUpload to parse the multpart form data requests. It has an excellent User Guide and 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来解析multpart表单数据请求。它有一个优秀的用户指南和FAQ(仔细地浏览这两个)。还有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.

你最初的尝试失败了很可能是因为你忘记了commons IO。

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

这里有一个kickoff的例子,说明UploadServlet的doPost()在使用Apache Commons 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将获得一个空请求体。还可以看到a.o. 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 Filter which 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.

或者,您也可以将其打包在一个过滤器中,它可以自动地解析它,并将这些东西放到请求的参数映射中,这样您就可以继续使用request. getparameter()方法,并通过request. getattribute()来检索已上传的文件。你可以在这篇博客文章中找到一个例子。

Workaround for GlassFish3 bug of getParameter() still returning null

Note that Glassfish versions older than 3.1.2 had a bug wherein 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()!)

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

对于正确保存获得的InputStream(如上面的代码片段所示的fileContent变量)到磁盘或数据库的详细信息,请访问下面的答案:

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

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

希望这一切都有帮助:)

#2


22  

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 enctype attribute set to "multipart/form-data" (Same as BalusC's Answer)

使用带有enctype属性的表单,设置为“多部分/表单数据”(与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 file to MultipartFile type as follows:

在您的控制器中,将请求参数文件映射到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
    }
}

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

您可以使用MultipartFile的getOriginalFilename()和getSize()获得文件名和大小。

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

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

#3


11  

You need the common-io.1.4.jar file to be included in your lib directory, 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.jar file just google it or just go to the Apache Tomcat website 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文件。

#4


8  

I am Using common Servlet for every Html Form whether it has attachments or not. This Servlet returns a TreeMap where 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名称参数,值是用户输入,并保存在固定目录中的所有附件,稍后您将重新命名您选择的目录。这里的连接是我们的自定义接口具有连接对象。我想这对你有帮助。

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

#5


6  

Without component or external Library in Tomcat 6 o 7

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

Enabling Upload in the web.xml file:

启用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/启用% 20文件% 20上传。

<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 File or 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-size and other options that you can to set...

编辑您的代码到servlet需求,如max文件大小,max-request-size和其他您可以设置的选项…

#6


6  

For Spring MVC I have been trying for hours to do this and managed to have a simpler version that worked for taking form input both data and image.

对于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 to handle

控制器处理

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

Hope it helps :)

希望它能帮助:)

#7


5  

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,则会出现另一个问题。在这种情况下,经过多次测试common -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的列表类型已经随着common -fileupload的当前版本进行了更改,以具体列出 ,而不是以前的版本。

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.

我将common -fileupload和common- io的源代码添加到Eclipse项目中,以跟踪实际的错误,并最终获得了一些见解。首先,抛出的异常是类型转换,而不是声明的FileIOException,也不是异常(这些将不会被捕获)。其次,错误消息是模糊的,因为它声明的类没有找到,因为axis2无法找到common -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.

最后,我找到了一个工作解决方案,成功地解决了我的问题。在部署计划中,必须将jar隐藏在父加载器中。这被放进了geronimoweb。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>

#8


0  

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

#9


-1  

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

}

#10


-1  

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

#11


-2  

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",并在输入标签中发送多个文件使用多个="多个"。

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

#12


-2  

HTML PAGE

HTML页面

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

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

web . xml

Compile above servlet UploadServlet and create required entry in web.xml file as follows.

编译上面的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>