web-dev-qa-db-fra.com

Comment télécharger des fichiers sur le dossier du serveur en utilisant jsp

J'essaie de télécharger des images sur un dossier qui se trouve sur mon serveur à l'aide de servlet/jsp.

Voici mon code, qui travaille sur ma machine locale:

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

Maintenant, mon code jsp, où je télécharge un fichier:

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

Dans mon fichier web.xml, j'ai inclus le chemin comme ceci:

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

J'ai utilisé le chemin de mon serveur http://grand-shopping.com/ <"un dossier">, mais cela ne fonctionne pas du tout ici.

Les bibliothèques que j'utilise sont:

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

Est-ce que n'importe qui peut me suggérer, comment exactement je dois définir mon chemin de serveur, afin de télécharger des images avec succès.

10
puneetjava

Le code ci-dessous fonctionne sur mon serveur live ainsi que sur mon propre Lapy.

Remarque:

Veuillez créer le dossier data dans WebContent et insérer n'importe quelle image ou fichier (fichier jsp ou html).

Ajouter des fichiers 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>
16
Vishal Shah
public class FileUploadExample extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

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

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

                try {
                    // Parse the request
                    List items = upload.parseRequest(request);
                    Iterator iterator = items.iterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (!item.isFormField()) {
                            String fileName = item.getName();    
                            String root = getServletContext().getRealPath("/");
                            File path = new File(root + "/uploads");
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            System.out.println(uploadedFile.getAbsolutePath());
                            item.write(uploadedFile);
                        }
                    }
                } catch (FileUploadException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

}
1
Vicky

Vous ne pouvez pas télécharger comme ça.

http://grand-shopping.com/<"some folder">

Vous avez besoin d’un chemin physique exactement comme dans votre section locale.

C:/Users/puneet verma/Downloads/

Ce que vous pouvez faire est de créer un chemin local sur lequel votre serveur fonctionne. Par conséquent, vous pouvez stocker et récupérer le fichier. Si vous avez acheté un domaine sur un site Web, il y aura un chemin pour télécharger les fichiers. Vous créez ces variables en tant que constante statique et vous les utilisez en fonction du serveur sur lequel vous travaillez (local/site Web).

0
Vinoth Krishnan

J'ai trouvé le problème similaire et trouvé la solution et j'ai blogué sur la façon de télécharger le fichier en utilisant JSP , Dans cet exemple, j'ai utilisé le chemin absolu. Notez que si vous souhaitez router vers un autre emplacement basé sur une URL, vous pouvez mettre un ESB tel que WSO2 ESB

0
Vanji

Vous pouvez uniquement utiliser un chemin absolu http://grand-shopping.com/ <"un dossier"> n'est pas un chemin absolu.

Soit vous pouvez utiliser un chemin d'accès dans l'application qui est visible .__ ou vous pouvez utiliser un chemin spécifique au serveur comme dans 

windows -> C:/Users/puneet verma/Downloads/
linux -> /opt/Downloads/
0
Dev