Table des matières
- Partie 1
Premiers pas avec Java EE
- Partie 2
Comprendre les Servlets et les JSPs
- Partie 3
Des vues puissantes avec la JSTL
- Partie 4
Développer une application web
- Partie 5
Enregistrer dans une base de données
Envoyer des fichiers
Téléchargez le fichier audiodescription : Partie 4, Chapitre 2
Vous trouverez sous la vidéo les codes source du cours.
Codes source
Le fichier web.xml qui configure notamment la taille maximale des uploads :
<?xml version="1.0" encoding="UTF-8"?>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1"
Test
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
Test
com.octest.servlets.Test
/Users/mateo21/fichierstmp/ <!-- A adapter chez vous -->
10485760 <!-- 10 Mo -->
52428800 <!-- 5 x 10 Mo -->
1048576 <!-- 1 Mo -->
Test
/bonjour
La servlet Test.java qui gère ici l'upload :
package com.octest.servlets;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.octest.forms.ConnectionForm;
/**
* Servlet implementation class Test
*/
@WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final int TAILLE_TAMPON = 10240;
public static final String CHEMIN_FICHIERS = "/Users/mateo21/fichiers/"; // A changer
public Test() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
// On récupère le champ description comme d'habitude
String description = request.getParameter("description");
request.setAttribute("description", description );
// On récupère le champ du fichier
Part part = request.getPart("fichier");
// On vérifie qu'on a bien reçu un fichier
String nomFichier = getNomFichier(part);
// Si on a bien un fichier
if (nomFichier != null && !nomFichier.isEmpty()) {
String nomChamp = part.getName();
// Corrige un bug du fonctionnement d'Internet Explorer
nomFichier = nomFichier.substring(nomFichier.lastIndexOf('/') + 1)
.substring(nomFichier.lastIndexOf('\\') + 1);
// On écrit définitivement le fichier sur le disque
ecrireFichier(part, nomFichier, CHEMIN_FICHIERS);
request.setAttribute(nomChamp, nomFichier);
}
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
private void ecrireFichier( Part part, String nomFichier, String chemin ) throws IOException {
BufferedInputStream entree = null;
BufferedOutputStream sortie = null;
try {
entree = new BufferedInputStream(part.getInputStream(), TAILLE_TAMPON);
sortie = new BufferedOutputStream(new FileOutputStream(new File(chemin + nomFichier)), TAILLE_TAMPON);
byte[] tampon = new byte[TAILLE_TAMPON];
int longueur;
while ((longueur = entree.read(tampon)) > 0) {
sortie.write(tampon, 0, longueur);
}
} finally {
try {
sortie.close();
} catch (IOException ignore) {
}
try {
entree.close();
} catch (IOException ignore) {
}
}
}
private static String getNomFichier( Part part ) {
for ( String contentDisposition : part.getHeader( "content-disposition" ).split( ";" ) ) {
if ( contentDisposition.trim().startsWith( "filename" ) ) {
return contentDisposition.substring( contentDisposition.indexOf( '=' ) + 1 ).trim().replace( "\"", "" );
}
}
return null;
}
}
Enfin, voici notre formulaire dans la JSP :
page pageEncoding="UTF-8"
taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"
<!DOCTYPE html>
charset="utf-8"
Test
test="${ !empty fichier }" value="Le fichier ${ fichier } (${ description }) a été uploadé !"
method="post" action="bonjour" enctype="multipart/form-data"
for="description"Description du fichier :
type="text" name="description" id="description"
for="fichier"Fichier à envoyer :
type="file" name="fichier" id="fichier"
type="submit"
Et si vous obteniez un diplôme OpenClassrooms ?
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel
Trouvez la formation et le financement faits pour vous