IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Java Discussion :

Afficher une image dans le cas d'un multipartfile


Sujet :

Spring Java

  1. #1
    Membre averti
    Femme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2011
    Messages
    593
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Juin 2011
    Messages : 593
    Points : 353
    Points
    353
    Par défaut Afficher une image dans le cas d'un multipartfile
    Bonjour,

    Dans mon formulaire, je propose à l'utilisateur d'uploader une image. Cette image est de type MultipartFile. Maintenant, je souhaiterais afficher cette image. Comment faire?
    J'ai fait:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    <img src="${nouvelleAnnonceBean.imagePrincipale}" />
    Mais ça ne marche pas...
    Help please?

  2. #2
    Membre à l'essai
    Inscrit en
    Août 2007
    Messages
    10
    Détails du profil
    Informations forums :
    Inscription : Août 2007
    Messages : 10
    Points : 16
    Points
    16
    Par défaut
    Bonjour,

    Il faut que tu regarde du code des servlets.

    Voici un exemple que j'ai trouvé et utilisé à cette adresse:
    http://balusc.blogspot.com/2007/07/fileservlet.html

    Dans un fichier ImageServlet.java:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
     
    package org.pbol.uhe.web.servlet;
     
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.Closeable;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.net.URLDecoder;
    import java.util.logging.FileHandler;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    /**
     * The Image servlet for serving from absolute path.
     * @author BalusC
     * @link http://balusc.blogspot.com/2007/04/imageservlet.html
     */
    @SuppressWarnings("serial")
    public class ImageServlet extends HttpServlet {
     
        // Constants ----------------------------------------------------------------------------------
     
        private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
     
        // Properties ---------------------------------------------------------------------------------
     
        private String imagePath;
     
        // Actions ------------------------------------------------------------------------------------
     
        protected static Logger logger = Logger.getLogger("ImageProcessing");
     
        public void init() throws ServletException {
     
            // Define base path somehow. You can define it as init-param of the servlet.
            this.imagePath = "c:\\repository\\photo";
     
            /*
    		 * 
    		 */
    		Handler fh = null;
    		try {
    			fh = new FileHandler(getClass().getSimpleName()+".log");
    		} catch (SecurityException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		logger.addHandler(fh);
    		/*
    		 * 
    		 */
    		logger.log(Level.WARNING, "ImageServlet init");
     
     
            // In a Windows environment with the Applicationserver running on the
            // c: volume, the above path is exactly the same as "c:\images".
            // In UNIX, it is just straightforward "/images".
            // If you have stored files in the WebContent of a WAR, for example in the
            // "/WEB-INF/images" folder, then you can retrieve the absolute path by:
            // this.imagePath = getServletContext().getRealPath("/WEB-INF/images");
        }
     
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        {
            // Get requested image by path info.
            String requestedImage = request.getPathInfo();
            logger.log(Level.WARNING, "ici1");
            // Check if file name is actually supplied to the request URI.
            if (requestedImage == null) {
                // Do your thing if the image is not supplied to the request URI.
                // Throw an exception, or send 404, or show default/warning image, or just ignore it.
                response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
                return;
            }
            logger.log(Level.WARNING, "ici2");
            // Decode the file name (might contain spaces and on) and prepare file object.
            File image = new File(imagePath, URLDecoder.decode(requestedImage, "UTF-8"));
     
            // Check if file actually exists in filesystem.
            if (!image.exists()) {
                // Do your thing if the file appears to be non-existing.
                // Throw an exception, or send 404, or show default/warning image, or just ignore it.
                response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
                return;
            }
            logger.log(Level.WARNING, "ici3");
            // Get content type by filename.
            String contentType = getServletContext().getMimeType(image.getName());
     
            // Check if file is actually an image (avoid download of other files by hackers!).
            // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
            if (contentType == null || !contentType.startsWith("image")) {
                // Do your thing if the file appears not being a real image.
                // Throw an exception, or send 404, or show default/warning image, or just ignore it.
                response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
                return;
            }
            logger.log(Level.WARNING, "ici4");
            // Init servlet response.
            response.reset();
            response.setBufferSize(DEFAULT_BUFFER_SIZE);
            response.setContentType(contentType);
            response.setHeader("Content-Length", String.valueOf(image.length()));
            response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
            logger.log(Level.WARNING, "ici5");
            // Prepare streams.
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
     
            try {
                // Open streams.
                input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
                output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
                logger.log(Level.WARNING, "ici6");
                // Write file contents to response.
                byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
                int length;
                while ((length = input.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                logger.log(Level.WARNING, "ici7");
            } finally { 
                // Gently close streams.
                close(output);
                close(input);
                logger.log(Level.WARNING, "ici close");
            }
        }
     
        // Helpers (can be refactored to public utility class) ----------------------------------------
     
        private static void close(Closeable resource) {
            if (resource != null) {
                try {
                    resource.close();
                } catch (IOException e) {
                    // Do your thing with the exception. Print it, log it or mail it.
                    e.printStackTrace();
                }
            }
        }
     
    }
    Dans le fichier web.xml:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    <servlet>
    	    <servlet-name>imageServlet</servlet-name>
    	    <servlet-class>org.pbol.uhe.web.servlet.ImageServlet</servlet-class>
    	</servlet>
    	<servlet-mapping>
    	    <servlet-name>imageServlet</servlet-name>
    	    <url-pattern>/photo/*</url-pattern>
    	</servlet-mapping>
    Bon courage

  3. #3
    Membre averti
    Femme Profil pro
    Développeur informatique
    Inscrit en
    Juin 2011
    Messages
    593
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Juin 2011
    Messages : 593
    Points : 353
    Points
    353
    Par défaut
    Super
    Merci beaucoup!

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Afficher une image dans un état
    Par Invité1 dans le forum IHM
    Réponses: 8
    Dernier message: 23/09/2009, 14h59
  2. [MFC]Afficher une image dans un Picture
    Par Cirdan Telemnar dans le forum MFC
    Réponses: 3
    Dernier message: 24/04/2006, 16h40
  3. comment afficher une image dans un jpanel ?
    Par 180degrés dans le forum AWT/Swing
    Réponses: 7
    Dernier message: 18/04/2006, 15h33
  4. Afficher une image dans un état
    Par louis_figos dans le forum IHM
    Réponses: 5
    Dernier message: 09/03/2006, 11h09
  5. Besoin d'aide pour afficher une image dans un applet
    Par argon dans le forum AWT/Swing
    Réponses: 16
    Dernier message: 19/01/2006, 19h45

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo