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

Persistance des données Java Discussion :

Chemin upload fichier vers bdd


Sujet :

Persistance des données Java

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mai 2017
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 31
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : Finance

    Informations forums :
    Inscription : Mai 2017
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Chemin upload fichier vers bdd
    Bonjour,

    Dans le cadre d'un site web je teste l'upload d'un fichier vers ma BDD.
    Lorsque je suis en local tout marche nickel, mais quand je met à jours mon site sur heroku ( bdd hebergée par amazom pour heroku) cela ne marche pas.
    La raison : dans mon code java, je demande à l'image d'être stockée en local sur mon ordinateur.
    Mon problème est le suivant : quel chemin dois indiquer, et que devrais je modifier dans ma bdd pour que mon fichier s'upload sur la bdd ?
    J'ai déjà fais de recherche mais je trouve pas de reponse à mon cas précis.
    J'utilise Thymeleaf dans un maven project.

    J'ose espérer que la solution est vraiment simple, seulement c'est bien frustrant de ne pas la trouver :/

    Merci pour votre aide,
    Bonne soiree

    Je joins ici la page de test html que j'ai fais pour m'afficher mes images, ainsi que les servlet et methodes java.
    Code affichage la liste de mes images sous forme de minis articles : 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
     
     
    @WebServlet("/home2")
    public class HomeServlet extends AbstractGenericServlet2 {
     
    	private static final long serialVersionUID = 5402133218271984030L;
     
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		TemplateEngine templateEngine = this.createTemplateEngine(req);
     
    		WebContext context = new WebContext(req, resp, getServletContext());
     
     
    		context.setVariable("images", InformationLibrary.getInstance().listAllImages());
     
     
     
     
    		templateEngine.process("home", context, resp.getWriter());
    	}
     
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		String countryString = req.getParameter("countryFilter");
     
     
     
    		resp.sendRedirect("home2");
     
    	}
     
     
     
    }

    Code servlet pour le chemin de mon fichier : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    @WebServlet("/imagepicture")
    public class CityPictureServlet extends AbstractGenericServlet2 {
     
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		Integer imageId = Integer.parseInt(req.getParameter("id"));
    		Path picturePath = InformationLibrary.getInstance().getPicturePatch(imageId);
     
    		Files.copy(picturePath, resp.getOutputStream());
    	}
     
     
    }

    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
    package marquise.servlets;
     
     
    @WebServlet("/imagepicture")
    public class CityPictureServlet extends AbstractGenericServlet2 {
     
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		Integer imageId = Integer.parseInt(req.getParameter("id"));
    		Path picturePath = InformationLibrary.getInstance().getPicturePatch(imageId);
     
    		Files.copy(picturePath, resp.getOutputStream());
    	}
     
     
    }
    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
    package marquise.servlets;
     
     
    @WebServlet("/detail")
    public class CityDetailServlet extends AbstractGenericServlet2 {
     
    	private static final long serialVersionUID = 8559083626521311046L;
     
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		TemplateEngine templateEngine = this.createTemplateEngine(req);
     
    		WebContext context = new WebContext(req, resp, getServletContext());
     
    		Integer idImage = Integer.parseInt(req.getParameter("id"));
    		context.setVariable("image", InformationLibrary.getInstance().getImage(idImage));		
    		//context.setVariable("comments", InformationLibrary.getInstance().listCommentsByCity(idCity));
    		context.setVariable("comments", InformationLibrary.getInstance().listAllImages());
     
     
     
    		templateEngine.process("imagedetail", context, resp.getWriter());
    	}
     
    	@Override
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
    			Integer cityId = Integer.parseInt(req.getParameter("id"));
     
     
     
    			resp.sendRedirect(String.format("detail?id=%d", cityId));
     
    			resp.sendRedirect("home2");
    		}
    }
    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
    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="utf-8">
    <title>City Explorer</title>
    <link rel="stylesheet" href="bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="fontawesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="css/custom.css">
     
    </head>
    <body>
    	<header th:replace="~{common::header}"></header>
     
    	<div id="mainContent" class="container-fluid">
    		<section class="cityfilters">
    			<h3>Filters</h3>
    			<form class="form-inline" method="post">
    				<div class="form-group">
    					<label for="countryInput">Country</label>
    					<select class="form-control" id="countryInput" name="countryFilter">
    						<option value="">All countries</option>
    						<option th:each="country : ${countries}" th:value="${country}" th:selected="${countryFilterSelected} == ${country}">[[${country.label}]]</option>
    					</select>
    				</div>
    				<input type="submit" class="btn btn-default" value="Filter">
    			</form>
    		</section>
    		<section class="citylist">
    			<article class="citybox" th:each="image : ${images}">
    				<h3>
    					[[${image.name}]] 
    					<a th:href="'deleteimage?id='+${image.id}" class="btn btn-xs btn-danger pull-right"> 
    						<i class="fa fa-times" aria-hidden="true"></i>
    					</a>
    				</h3>
    				<p th:text="${image.summary}" class="summary"></p>
    				<div class="btn-toolbar actionbar" role="toolbar">
    					<div class="btn-group" role="group">
    						<a th:href="'detail?id='+${image.id}" class="btn btn-primary"><i
    							class="fa fa-eye" aria-hidden="true"></i> See details</a>
    					</div>
     
    				</div>
    				<aside class="cityPhoto">
    					<img th:src="'imagepicture?id='+${image.id}" th:alt="'Vignette '+${image.name}">
    				</aside>
    			</article>
    		</section>
    	</div>
    </body>
    </html>
    Code library avec le fameux chemin vers mon repertoire : 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
    156
     
    public class InformationLibrary {
     
     
    	private static class InformationLibraryHolder{
    		private final static InformationLibrary instance = new InformationLibrary();
     
    	}
     
    	public static InformationLibrary getInstance(){
    		return InformationLibraryHolder.instance;
    	}
     
    	private InformationDao informationDao = new InformationDaoImpl();
    	private UtilisateurDao utilisateurDao = new UtilisateurDaoImpl();
    	private CommentaireDao commentaireDao = new CommentaireDaoImpl();
    	private ArticleDao articleDao = new ArticleDaoImpl();
    	private IdentifiantDao identifiantDao = new IdentifiantDaoImpl();
    	private ImageDao imageDao = new ImageDao();
     
     
    	private static final String PICTURE_MAIN_DIRECTORY = "/Users/louiscauvray/git/projet/src/main/resources";
     
     
    	private ElementsSiteDao elementsSiteDao = new ElementsSiteDao();
     
    	private InformationLibrary() {
    	}
     
     
            //Recuperer les informations sur les utilisateurs
     
    	public List<Information> listFilms() {
    		return informationDao.listInformations();
    	}
     
    	public Information getInformation(Integer id) {
    		return informationDao.getInformation(id);
    	}
     
    	public Information addInformation(Information information) {
    		return informationDao.addInformation(information);
    	}
     
    	public List<Utilisateur> listUtilisateurs() {
    		return utilisateurDao.listUtilisateurs();
    	}
     
    	public Utilisateur getUtilisateur(Integer id) {
    		return utilisateurDao.getUtilisateur(id);
    	}
    	public Utilisateur getUtilisateurByNom(String nom){
    		return utilisateurDao.getUtilisateurByNom(nom);
    	}
     
    	public Utilisateur addUtilisateur(String nom, String prenom) {
    		return utilisateurDao.addUtilisateur(nom, prenom);
    	}
            //Gerer les commentaires visible en backoffice
     
    	public List<Commentaire> listCommentaires(){
    		return commentaireDao.listCommentaires();
    	}
     
    	public Commentaire addCommentaire(String email ,String commentaire){
    		return commentaireDao.addCommentaire(email, commentaire);
    	}
     
    	public List<Article> listArticles(){
    		return articleDao.listArticles();
     
    	}
     
    	public Article addArticle(String title, String texte, LocalDate datePublication, String auteur) {
    		return articleDao.addArticle(title, texte, datePublication, auteur);
    	}
     
    	public Identifiant getIdentifiant(String login, String motDePasse){
    		return identifiantDao.getIdentifiant(login, motDePasse);
     
    	}
     
    	//Methode pour appeler les image et les chemins des images
     
    	public List<Image> listAllImages() {
     
    			return imageDao.listImages();
    	}
     
    	public Image getImage(Integer id) {
    		if(id == null) {
    			throw new IllegalArgumentException("Image id must be provided.");
    		}
    		return imageDao.getImage(id);
    	}
     
    	public void addImage(Image newImage, Part picture) throws IOException {
    		if(newImage == null){
    			throw new IllegalArgumentException("An image must be provided.");
    		}
    		if(newImage.getName() == null || "".equals(newImage.getName())) {
    			throw new IllegalArgumentException("An image must have a name.");
    		}
    		if(newImage.getSummary() == null || "".equals(newImage.getSummary())) {
    			throw new IllegalArgumentException("An image must have a summary.");
    		}
    		if(picture == null){
    			throw new IllegalArgumentException("An image must contain a picture.");
    		}
     
    		Path picturePath = Paths.get(PICTURE_MAIN_DIRECTORY, picture.getSubmittedFileName());
     
    		imageDao.addImage(newImage, picturePath.toString());
     
     
    		Files.copy(picture.getInputStream(), picturePath);
     
     
    	}
     
    	public Path getPicturePatch(Integer imageId) {
    		String picturePathString = imageDao.getPicturePath(imageId);
    		if(picturePathString == null) {
    			return getDefaultPicturePath();
    		} else {
    			Path picturePath = Paths.get(imageDao.getPicturePath(imageId));
    			if(Files.exists(picturePath)) {
    				return picturePath;
    			} else {
    				return getDefaultPicturePath();
    			}
    		}
     
    	}
     
    	private Path getDefaultPicturePath() {
    		try {
    			return Paths.get(this.getClass().getClassLoader().getResource("city-no-photo.png").toURI());
    		} catch (URISyntaxException e) {
    			return null;
    		}
    	}
     
    	// ElementsSite Dao
    		public void modifierElementTexte(String idElement, String contenuElement) {
    			elementsSiteDao.modifierElementTexte(idElement, contenuElement);
    		}
     
    		public void modifierElementImage(String idElement, String contenuElement, String cheminElement) {
    			elementsSiteDao.modifierElementImage(idElement, contenuElement, cheminElement);
    		}
     
    		public ElementsSite getElementById(String id) {
    			return elementsSiteDao.getElementById(id) ;
    		}
    }
    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
     
    package marquise.daos;
     
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
     
     
     
     
     
    import marquise.daos.impl.DataSourceProvider;
    import marquise.exceptions.CityExplorerRuntimeException;
    import marquise.projos.Image;
     
    public class ImageDao {
     
    	public List<Image> listImages() {
    		List<Image> images = new ArrayList<Image>();
     
    		try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
    				Statement statement = connection.createStatement();
    				ResultSet resultSet = statement.executeQuery("SELECT * FROM image ORDER BY name")) {
    			while (resultSet.next()) {
     
    				images.add(
    						new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary")));
    			}
    		} catch (SQLException e) {
    			throw new CityExplorerRuntimeException("Error when getting images", e);
    		}
     
    		return images;
    	}
     
    	public Image getImage(Integer id) {
    		try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
    				PreparedStatement statement = connection.prepareStatement("SELECT * FROM image WHERE id = ?")) {
    			statement.setInt(1, id);
    			try (ResultSet resultSet = statement.executeQuery()) {
    				if (resultSet.next()) {
     
    					return new Image(resultSet.getInt("id"), resultSet.getString("name"), resultSet.getString("summary"));
    				}
    			}
    		} catch (SQLException e) {
    			throw new CityExplorerRuntimeException("Error when getting images", e);
    		}
    		return null;
    	}
     
    	public void addImage(Image newImage, String picturePath) {
    		try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
    				PreparedStatement statement = connection.prepareStatement("INSERT INTO image(name, summary, picture) VALUES (?, ?, ?)")) {
    			statement.setString(1, newImage.getName());
    			statement.setString(2, newImage.getSummary());
    			statement.setString(3, picturePath);
    			statement.executeUpdate();
    		} catch (SQLException e) {
    			throw new CityExplorerRuntimeException("Error when getting images", e);
    		}
    	}
    	public String getPicturePath(Integer id) {
    		try (Connection connection = DataSourceProvider.getInstance().getDataSource().getConnection();
    				PreparedStatement statement = connection.prepareStatement("SELECT picture FROM image WHERE id = ?")) {
    			statement.setInt(1, id);
    			try (ResultSet resultSet = statement.executeQuery()) {
    				if (resultSet.next()) {
    					return resultSet.getString("picture");
    				}
    			}
    		} catch (SQLException e) {
    			throw new CityExplorerRuntimeException("Error when getting images", e);
    		}
    		return null;
    	}
     
    }

  2. #2
    Membre expérimenté Avatar de Nico02
    Homme Profil pro
    Developpeur Java/JEE
    Inscrit en
    Février 2011
    Messages
    728
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hérault (Languedoc Roussillon)

    Informations professionnelles :
    Activité : Developpeur Java/JEE
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2011
    Messages : 728
    Points : 1 622
    Points
    1 622
    Par défaut
    Salut,

    Le problème c'est que visiblement tu essais de donner un Path vers une image stockée sur ta machine à un serveur pour qu'il l'utilise. Ça ne pourra jamais marcher, pour la simple raison que ton serveur n'a aucun moyen d'accéder à ta machine (il ne la connais même pas).
    En faisant comme tu le fais, ton code va chercher l'image sur le serveur lui même.

    Tu n'a pas d'autres choix que de mettre tes images sur ton serveur.

    Peux-tu expliquer pourquoi tu veux garder tes images en local ?

Discussions similaires

  1. upload fichiers vers ftp
    Par saphi dans le forum Langage
    Réponses: 2
    Dernier message: 13/09/2009, 02h10
  2. upload fichier vers serveur linux
    Par nadine7 dans le forum Import/Export
    Réponses: 1
    Dernier message: 14/08/2009, 13h03
  3. Upload fichier vers site WSS
    Par Pietr_Alekseievitch dans le forum SharePoint
    Réponses: 9
    Dernier message: 13/11/2008, 22h28
  4. Upload fichier vers Free ?
    Par Ramdoulou dans le forum VB 6 et antérieur
    Réponses: 13
    Dernier message: 09/08/2008, 19h51
  5. importe fichier vers bdd
    Par ulysse031 dans le forum SQL Procédural
    Réponses: 0
    Dernier message: 27/12/2007, 17h17

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