如何使用jsp上传服务器文件夹中的文件 [英] How to upload files on server folder using jsp

查看:22
本文介绍了如何使用jsp上传服务器文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 servlet/jsp 在位于我的服务器上的文件夹中上传一些图像.

I am trying to upload some images on folder which locates on my server using servlet/jsp.

下面是我的代码,它在我的本地机器上运行:

Below is my code, which is working on my local machine:

 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 = 1000 * 1024;
   private int maxMemSize = 1000 * 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:/Users/puneet verma/Downloads/"));  

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

现在我的jsp代码,我上传文件的地方:

Now my jsp code, where i upload file:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
   <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>

在我的 web.xml 文件中,我包含了这样的路径:

In My web.xml file, I've included path like this:

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

我使用了我的服务器路径 http://grand-shopping.com/<"some folder"> ,但是它在这里根本不起作用.

I've used my server path http://grand-shopping.com/<"some folder"> , but it's not working here at all.

我使用的库是:

  1. commons-fileupload-1.3.jar
  2. commons-io-2.2.jar

谁能建议我,我需要如何定义我的服务器路径,才能成功上传图片.

Can anyone suggest me , how exactly i need to define my server path, in order to upload images successfully.

推荐答案

下面的代码在我的实时服务器和我自己的 Lapy 上都有效.

注意:

请在 WebContent 中创建 data 文件夹并放入任何单个图像或任何文件(jsp 或 html 文件).

Please Create data folder in WebContent and put in any single image or any file(jsp or html file).

添加jar文件

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

commons-collections-3.1.jar
commons-fileupload-1.2.2.jar
commons-io-2.1.jar
commons-logging-1.0.4.jar

upload.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="dataFile" id="fileChooser"/><br/><br/>
<input type="submit" value="Upload" />
</form>
</body>
</html>

UploadServlet.java

package com.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

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;

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

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

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

        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (!isMultipart) {
            return;
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Sets the size threshold beyond which files are written directly to
        // disk.
        factory.setSizeThreshold(MAX_MEMORY_SIZE);

        // Sets the directory used to temporarily store files that are larger
        // than the configured size threshold. We use temporary directory for
        // java
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        // constructs the folder where uploaded file will be stored
        String uploadFolder = getServletContext().getRealPath("")
                + File.separator + DATA_DIRECTORY;

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        try {
            // Parse the request
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    File uploadedFile = new File(filePath);
                    System.out.println(filePath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                }
            }

            // displays done.jsp page after upload finished
            getServletContext().getRequestDispatcher("/done.jsp").forward(
                    request, response);

        } catch (FileUploadException ex) {
            throw new ServletException(ex);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }

    }

}

web.xml

  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>com.servlet.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

done.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Done</title>
</head>
<body>
<h3>Your file has been uploaded!</h3>
</body>
</html>

这篇关于如何使用jsp上传服务器文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆