【问题标题】:How to upload file to folder on server in jsp? [duplicate]如何在jsp中将文件上传到服务器上的文件夹? [复制]
【发布时间】:2012-11-16 06:53:23
【问题描述】:

我正在做项目在线图片库,我必须在其中上传图片。我用 jsp/servlet 做,IDE 是 Eclipse。 我的jsp文件如下

<form action="ActionPage" >
    <input type="file" name="myFile">

    <br>
    <input type="submit">
</form>

这里的 Actionpage 是 servlet。在单击提交按钮时,我希望将所选文件存储在服务器上的 WebContent 内名为“IMAGE”的文件夹中,并在数据库表上存储路径。 如果有人知道简单的解决方案,请分享。

提前致谢。

【问题讨论】:

    标签: eclipse jsp servlets file-upload


    【解决方案1】:

    您可以在此处阅读这是如何完成的

    How to upload files to server using JSP/Servlet?

    PS:在应用程序目录中存储上传的文件是不好的坏主意。想想如果您的应用程序运行了一段时间会发生什么,并且您想要重新部署,因为文件缺少一些 html 标记。上传的目录将被您的容器删除! 尝试使用应用程序目录之外的文件夹,或使用数据库。

    【讨论】:

    • 谢谢。好的,那么将该文件存储到文件夹的代码是什么。
    • 您会在我发布的链接中的@BalusC 答案中找到您需要的一切。无需添加重复内容
    【解决方案2】:

    如果您使用 jsp 开发您的网站,这是最简单的解决方案 首先,从用户那里获取输入,制作一个 html 或 jsp 页面,并在您的 jsp/html 页面中包含 tis 代码

    首先下载

    • commons-fileupload-1.2.2.jar

    • org.apache.commons.io.jar

    并通过右键单击您的项目然后选择构建路径然后添加 jar 文件来将此 jar 添加到您的库中

        `<form role="form" action="Upload.jsp" method="post"enctype="multipart/form-data">
        <div class="btn btn-success btn-file">
        <i class="fa fa-cloud-upload"></i>
                 Browse
        <input type="file" name="file" />
        </div>
        <button type="submit" value="submit" name='submit'>submit</button>`
        </form>
    

    enctype="multipart/form-data" 很有必要

    现在创建一个名为upload.jsp的jsp(你可以使用目标jsp将我们的图像保存到任何名称的服务器,但记得在上面的代码中输入该名称

        <%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
        <%@ page import="javax.servlet.http.*" %>
        <%@ page import="org.apache.commons.fileupload.*" %>
        <%@ page import="org.apache.commons.fileupload.disk.*" %>
        <%@ page import="org.apache.commons.fileupload.servlet.*" %>
        <%@ page import="org.apache.commons.io.output.*" %>
    
        <%
           String userName = (String) session.getAttribute("User");
          File file ;
          int maxFileSize = 5000000 * 1024;
          int maxMemSize = 5000000 * 1024;
          ServletContext context = pageContext.getServletContext();
          String filePath = context.getInitParameter("file-upload");
    
          // 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("C:\\Users\\"));
    
      // 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<FileItem> fileItems = upload.parseRequest(request);
    
         // Process the uploaded file items
         Iterator i = fileItems.iterator();
    
         while ( i.hasNext () ) 
         {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () )   
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            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 ) ;
    
            request.setAttribute("Success", "Successfully Uploaded");
            RequestDispatcher rd = request.getRequestDispatcher("/UploadFiles.jsp");
            rd.forward(request, response);
            }
         }
    
      }catch(Exception ex) {
         System.out.println(ex);
      }
          }else{
             request.setAttribute("Error", "Error!!");
            RequestDispatcher rd =request.getRequestDispatcher("/UploadFiles.jsp");
            rd.forward(request, response);
          }
       %>
    

    请不要混淆,只需复制此代码即可,一旦您完成此操作,我相信您会了解代码

    现在你要做的最后一点是添加一些东西到 web.xml 如果你没有这个文件然后创建这个...

     <context-param>
        <description>Location to store uploaded file</description>
        <param-name>file-upload</param-name>
        <param-value>
                 C:\\Users\\
        </param-value>
    </context-param>
    

    只需将上述代码添加到 web.xml,您就可以根据需要更改上传图片的地址(为此更改参数值)

    如果您遇到任何问题,请告诉我

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 2015-02-27
      • 2016-03-20
      • 1970-01-01
      • 2016-06-18
      相关资源
      最近更新 更多