首页 文章

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

提问于
浏览
637

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

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

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

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

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

不幸的是,servlet抛出异常而没有明确的消息和原因 . 这是堆栈跟踪:

SEVERE: Servlet.service() for servlet UploadServlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:313)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:637)

12 回答

  • -2

    简介

    要浏览并选择要上载的文件,您需要在表单中使用HTML <input type="file"> 字段 . 如HTML specification中所述,您必须使用 POST 方法,并且表单的 enctype 属性必须设置为 "multipart/form-data" .

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

    提交此类表单后,二进制多部分表单数据在a different format中的请求正文中可用,而不是在未设置 enctype 时 .

    在Servlet 3.0之前,Servlet API本身不支持 multipart/form-data . 它仅支持 application/x-www-form-urlencoded 的默认表单enctype . 使用多部分表单数据时, request.getParameter() 和consorts都将返回 null . 这是众所周知的Apache Commons FileUpload进入画面的地方 .

    不要手动解析它!

    理论上,您可以根据ServletRequest#getInputStream()自己解析请求体 . 然而,这是一项精确而繁琐的工作,需要精确的RFC2388知识 . 你不应该试图自己做这个或者复制一些在互联网上其他地方找到的本土的无库代码 . 许多在线消息来源都很难,例如roseindia.net . 另见uploading of pdf file . 您应该使用数百万用户多年使用(并隐式测试!)的真实库 . 这样的库已经证明了它的稳健性 .

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

    如果您至少使用Servlet 3.0(Tomcat 7,Jetty 9,JBoss AS 6,GlassFish 3等),那么您可以使用提供的标准API HttpServletRequest#getPart()来收集单个多部分表单数据项(大多数Servlet 3.0实现实际使用) Apache Commons FileUpload为此提供了支持!) . 此外,通常的方式可以通过 getParameter() 获得普通表单字段 .

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

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

    然后,按如下方式实现 doPost()

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
        Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
        String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
        InputStream fileContent = filePart.getInputStream();
        // ... (do your job here)
    }
    

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

    如果您有多个文件上传的 <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())).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)
        }
    }
    

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

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

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

    当您还没有使用Servlet 3.0时,请使用Apache Commons FileUpload

    如果您有时间升级?),通常的做法是使用Apache Commons FileUpload来解析多部分表单数据请求 . 它有一个优秀的User GuideFAQ(仔细检查两者) . 有's also the O' Reilly(“cos”) MultipartRequest ,但它有一些(小的)错误,并且不推荐使用它 . Apache Commons FileUpload仍在积极维护,目前非常成熟 .

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

    您最初的尝试失败的可能性很大,因为您忘记了公共IO .

    以下是使用Apache Commons FileUpload时 UploadServletdoPost() 如何显示的启动示例:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    // ... (do your job here)
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fileName = FilenameUtils.getName(item.getName());
                    InputStream fileContent = item.getInputStream();
                    // ... (do your job here)
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }
    
        // ...
    }
    

    它's very important that you don' t事先在同一请求上调用 getParameter()getParameterMap()getParameterValues()getInputStream()getReader() 等 . 否则,servlet容器将读取并解析请求体,因此Apache Commons FileUpload将获得一个空的请求体 . 另见a.o. ServletFileUpload#parseRequest(request) returns an empty list .

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

    或者你也可以将这一切包装在一个 Filter 中,它自动解析它并将这些东西放回到请求的参数图中,这样你就可以继续使用 request.getParameter() 通常的方式并通过 request.getAttribute() 检索上传的文件 . You can find an example in this blog article .

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

    请注意,早于3.1.2的Glassfish版本具有a bug,其中 getParameter() 仍然返回 null . 如果您要定位此类容器但无法升级它,则需要在此实用程序的帮助下从 getPart() 中提取值方法:

    private static String getValue(Part part) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
        StringBuilder value = new StringBuilder();
        char[] buffer = new char[1024];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            value.append(buffer, 0, length);
        }
        return value.toString();
    }
    
    String description = getValue(request.getPart("description")); // Retrieves <input type="text" name="description">
    

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

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

    提供上传的文件

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

    Ajaxifying表单

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


    希望这一切都有帮助:)

  • 6

    Without component or external Library in Tomcat 6 o 7

    web.xml 文件中启用上载:

    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>
    

    如你看到的:

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

    Uploading Files using JSP. Files:

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

    在JSP文件或Servlet中

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

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

  • -1

    如果您碰巧使用Spring MVC,这是如何:(我将离开这里以防有人发现它有用) .

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

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

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

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public void handleUpload(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
                byte[] bytes = file.getBytes(); // alternatively, file.getInputStream();
                // application logic
        }
    }
    

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

    我用Spring版 4.1.1.RELEASE 测试了这个 .

  • 0

    这是使用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);
    
  • 25

    HTML PAGE

    <html>
    <head>
    <title>File Uploading Form</title>
    </head>
    <body>
    <h3>File Upload:</h3>
    Select a file to upload: 
    <form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file" size="50" />
    <input type="submit" value="Upload File" /> </form> </body> </html>

    SERVLET文件

    // Import required java libraries
    import java.io.*;
    import java.util.*;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.commons.io.output.*;
    
    public class UploadServlet extends HttpServlet {
    
       private boolean isMultipart;
       private String filePath;
       private int maxFileSize = 50 * 1024;
       private int maxMemSize = 4 * 1024;
       private File file ;
    
       public void init( ){
          // Get the file location where it would be stored.
          filePath = 
                 getServletContext().getInitParameter("file-upload"); 
       }
       public void doPost(HttpServletRequest request, 
                   HttpServletResponse response)
                  throws ServletException, java.io.IOException {
          // Check that we have a file upload request
          isMultipart = ServletFileUpload.isMultipartContent(request);
          response.setContentType("text/html");
          java.io.PrintWriter out = response.getWriter( );
          if( !isMultipart ){
             out.println("<html>");
             out.println("<head>");
             out.println("<title>Servlet upload</title>");  
             out.println("</head>");
             out.println("<body>");
             out.println("<p>No file uploaded</p>"); 
             out.println("</body>");
             out.println("</html>");
             return;
          }
          DiskFileItemFactory factory = new DiskFileItemFactory();
          // maximum size that will be stored in memory
          factory.setSizeThreshold(maxMemSize);
          // Location to save data that is larger than maxMemSize.
          factory.setRepository(new File("c:\\temp"));
    
          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
          // maximum file size to be uploaded.
          upload.setSizeMax( maxFileSize );
    
          try{ 
          // Parse the request to get file items.
          List fileItems = upload.parseRequest(request);
    
          // Process the uploaded file items
          Iterator i = fileItems.iterator();
    
          out.println("<html>");
          out.println("<head>");
          out.println("<title>Servlet upload</title>");  
          out.println("</head>");
          out.println("<body>");
          while ( i.hasNext () ) 
          {
             FileItem fi = (FileItem)i.next();
             if ( !fi.isFormField () )  
             {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if( fileName.lastIndexOf("\\") >= 0 ){
                   file = new File( filePath + 
                   fileName.substring( fileName.lastIndexOf("\\"))) ;
                }else{
                   file = new File( filePath + 
                   fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                }
                fi.write( file ) ;
                out.println("Uploaded Filename: " + fileName + "<br>");
             }
          }
          out.println("</body>");
          out.println("</html>");
       }catch(Exception ex) {
           System.out.println(ex);
       }
       }
       public void doGet(HttpServletRequest request, 
                           HttpServletResponse response)
            throws ServletException, java.io.IOException {
    
            throw new ServletException("GET method used with " +
                    getClass( ).getName( )+": POST method required.");
       } 
    }
    

    web.xml中

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

    <servlet>
       <servlet-name>UploadServlet</servlet-name>
       <servlet-class>UploadServlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
       <servlet-name>UploadServlet</servlet-name>
       <url-pattern>/UploadServlet</url-pattern>
    </servlet-mapping>
    
  • 9

    你可以使用jsp / servlet上传文件 .

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

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

    package com.abc..servlet;
    
    import java.io.File;
    ---------
    --------
    
    
    /**
     * Servlet implementation class UploadFileServlet
     */
    public class UploadFileServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        public UploadFileServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            response.sendRedirect("../jsp/ErrorPage.jsp");
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
    
                PrintWriter out = response.getWriter();
                HttpSession httpSession = request.getSession();
                String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
    
                String path1 =  filePathUpload;
                String filename = null;
                File path = null;
                FileItem item=null;
    
    
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
                if (isMultipart) {
                    FileItemFactory factory = new DiskFileItemFactory();
                    ServletFileUpload upload = new ServletFileUpload(factory);
                    String FieldName = "";
                    try {
                        List items = upload.parseRequest(request);
                        Iterator iterator = items.iterator();
                        while (iterator.hasNext()) {
                             item = (FileItem) iterator.next();
    
                                if (fieldname.equals("description")) {
                                    description = item.getString();
                                }
                            }
                            if (!item.isFormField()) {
                                filename = item.getName();
                                path = new File(path1 + File.separator);
                                if (!path.exists()) {
                                    boolean status = path.mkdirs();
                                }
                                /* START OF CODE FRO 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();
                    } 
                }   
        }
    
    }
    
  • -1

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

    fileItems = uploader.parseRequest(request);
    

    请注意,fileItems的List类型已更改,当前版本的commons-fileupload具体为 List<FileItem> ,而不是之前的版本 List .

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

    最后,我找到了一个提出成功解决问题的工作解决方案的地方 . 您必须在部署计划中隐藏来自父加载程序的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>
    
  • 8

    发送文件的多个文件我们必须使用 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>
    
  • 12

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

    要获取 common.io.jar 文件只是google它或只是去Apache Tomcat网站,您可以在其中获得免费下载此文件的选项 . 但请记住一件事:如果您是Windows用户,请下载二进制ZIP文件 .

  • -2

    我正在使用 every Html表单的公共Servlet是否有附件 . 此Servlet返回 TreeMap ,其中键是jsp名称参数和值是用户输入并将所有附件保存在固定目录中,稍后您重命名所选目录.Here 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;
        }
    }
    
  • 1105

    For Spring MVC 我已经尝试了几个小时来做这个并且设法有一个更简单的版本,用于表单输入数据和图像 .

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

    控制器处理

    @Controller
    public class FormController {
        @RequestMapping(value="/handleform",method= RequestMethod.POST)
        ModelAndView register(@RequestParam String name, @RequestParam int age, @RequestParam MultipartFile file)
                throws ServletException, IOException {
    
            System.out.println(name);
            System.out.println(age);
            if(!file.isEmpty()){
                byte[] bytes = file.getBytes();
                String filename = file.getOriginalFilename();
                BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("D:/" + filename)));
                stream.write(bytes);
                stream.flush();
                stream.close();
            }
            return new ModelAndView("index");
        }
    }
    

    希望能帮助到你 :)

  • 8
    DiskFileUpload upload=new DiskFileUpload();
    

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

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

相关问题