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

Struts 1 Java Discussion :

Problème de download d'un fichier à partir d'une JSP


Sujet :

Struts 1 Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    158
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 158
    Par défaut Problème de download d'un fichier à partir d'une JSP
    Bonjour,

    J'essaie d'exporter un fichier JSON (format proche de xml) à partir d'un clic sur un bouton à partir de mon jsp en passant par un OutputStream et un InputStream.
    Mes codes sources ci dessous:
    Action.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
     
    /** The inputStream */
    	private InputStream inputStream;
     
     
    public String exportToJsonFile()
    	throws JsonMappingException, JsonGenerationException, IOException
    		{
    		try {
    			Map<String, String> objectMap = new HashMap<String, String>();
    			if(isRoleBeanChecked() != null){
    				if(isRoleBeanChecked()){
    					Collection<RoleBean> roleList = this.getRoleBeanService().getListRoleBean();
    					String tmp = this.getRoleBeanService().exportIntoJson(roleList, false);
    					objectMap.put(roleBeanKey, tmp);
    				}
    			}
    			if(isProfileBeanChecked() != null){
    				if(isProfileBeanChecked()){
    					Collection<ProfileBean> profileList = this.getProfileBeanService().getListProfileBean();
    					String tmp = this.getProfileBeanService().exportIntoJson(profileList, false);
    					objectMap.put(profileBeanKey, tmp);
    				}
    			}
    			//String dataToJSON = this.getRootExportBeanService().exportToJsonFile(objectMap, prettyPrint);
    			String dataToJSON = this.getRootExportBeanService().exportToJsonFile(objectMap, true);
     
    			InputStream anInputStream = new ByteArrayInputStream(dataToJSON.getBytes("UTF-8"));
    			this.setInputStream(anInputStream);
     
     
    			byte[] bytes = this.inputStreamToByte(this.getInputStream());
     
    			this.sendDocumentToResponse(getServletResponse(), "testExport.txt", bytes);
     
    		}
    		catch (FileNotFoundException e) {
    			throw new RuntimeException(e);
    		} catch (StsException e) {
    			this.addActionError("ihm.message.internalError");
    		} /*catch (ServletException e) {
    			this.addActionError("ihm.message.servletError");
    			//e.printStackTrace();
    		}*/
     
    		this.addActionInfo("ihm.message.dataExported");
    		return SUCCESS;
     
    	}
     
    private void sendDocumentToResponse(HttpServletResponse response, String txtFile, byte[] documentTextBytes) {
     
    		OutputStream responseOutputStream = null;
    		int taille;
    		StringBuffer fileName;
    		try {
    			taille = documentTextBytes.length;
    			fileName = new StringBuffer();
    			fileName.append(txtFile);
    			//fileName.append(".txt");
     
    			response.setContentLength(taille);
    			response.setContentType("application/octet-stream");
    			response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\"");
    			response.setHeader("Pragma", "public");
    			response.setHeader("Cache-Control", "cache");
    			response.setHeader("Cache-control", "must-revalidate");
    			responseOutputStream = response.getOutputStream();
    			responseOutputStream.write(documentTextBytes);
     
    			responseOutputStream.flush();
    			responseOutputStream.close();
     
    		} catch (Exception e) {
    				try {
    					if (responseOutputStream != null) {
    						responseOutputStream.close();
    					}
    				} catch (IOException e1) {
    					}
    				}
    			}
     
    /**
             * @param inputStream the inputStream to set
             */
    	public void setInputStream(InputStream inputStream) {
    		this.inputStream = inputStream;
    	}
     
    	/**
             * @return the inputStream
             */
    	public InputStream getInputStream() {
    		return inputStream;
    	}
    mon Struts.xml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    <!-- BackupRestore Action -->
    		<action name="exportToJsonFile" class="rootExportBeanAction">
    			<result name="success" type="stream">
    			  <param name="contentType">application/octet-stream</param>
    			  <param name="inputName">inputStream</param>
    			  <param name="contentDisposition">attachment; filename="testExport.txt"</param>
    			  <param name="bufferSize">1024</param>
    			</result>
    		</action>
    		<action name="initExport" class="rootExportBeanAction" method="initExport">
    			<result name="success" type="tiles">InitExport</result>
    		</action>
    mon tile : InitExport

    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
     
    <fieldset>
    			<s:form action="getRootExportPopup" namespace="/">
    				<table>
    					<tr>
    						<td><table>
    							<s:checkbox labelposition="left" key="ihm.label.field.roleBeanChecked" 
    							name="roleBeanChecked" value="%{roleBeanChecked}" mode="E,E,E" />
    						</table></td>
    					</tr>
    					<tr>
    						<td><table>
    							<s:checkbox labelposition="left" key="ihm.label.field.profileBeanChecked"
    							name="profileBeanChecked" value="%{profileBeanChecked}" mode="E,E,E" />
    						</table></td>
    					</tr>
    				</table>
    			</s:form>
    		</fieldset>
     
    <table>
    	<tr>
    	<td>
    <s:submit value="Exporter" name="Exporter" method="exportToJsonFile"/></td>
     
    	</tr>
    </table>
    Le popup apparait et me demander d'enregistrer le fichier sur le disque, mais j'ai un message sur le console :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    ERROR [[jsp]] "Servlet.service()" pour la servlet jsp a lancé une exception
    java.lang.IllegalStateException: "getOutputStream()" a déjà été appelé pour cette réponse
    	at org.apache.catalina.connector.Response.getWriter(Response.java:604)
    	at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:198)
    	at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:112)
    	at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:112)
    	at 
     
    .....
    Merci d'avance.

  2. #2
    Membre confirmé
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    158
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 158
    Par défaut
    le problème est résolu :
    Action.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
    public String exportToJsonFile()
    	throws JsonMappingException, JsonGenerationException, IOException
    		{
    		try {
    			Map<String, String> objectMap = new HashMap<String, String>();
    			if(isRoleBeanChecked() != null){
    				if(isRoleBeanChecked()){
    					Collection<RoleBean> roleList = this.getRoleBeanService().getListRoleBean();
    					String tmp = this.getRoleBeanService().exportIntoJson(roleList, false);
    					objectMap.put(roleBeanKey, tmp);
    				}
    			}
    			if(isProfileBeanChecked() != null){
    				if(isProfileBeanChecked()){
    					Collection<ProfileBean> profileList = this.getProfileBeanService().getListProfileBean();
    					String tmp = this.getProfileBeanService().exportIntoJson(profileList, false);
    					objectMap.put(profileBeanKey, tmp);
    				}
    			}
    			//String dataToJSON = this.getRootExportBeanService().exportToJsonFile(objectMap, prettyPrint);
    			String dataToJSON = this.getRootExportBeanService().exportToJsonFile(objectMap, true);
     
    			InputStream anInputStream = new ByteArrayInputStream(dataToJSON.getBytes("UTF-8"));
    			this.setInputStream(anInputStream);
     
     
    			byte[] bytes = this.inputStreamToByte(this.getInputStream());
     
    			this.sendDocumentToResponse(getServletResponse(), "testExport.txt", bytes);
     
    		}
    		catch (FileNotFoundException e) {
    			throw new RuntimeException(e);
    		} catch (StsException e) {
    			this.addActionError("ihm.message.internalError");
    		} /*catch (ServletException e) {
    			this.addActionError("ihm.message.servletError");
    			//e.printStackTrace();
    		}*/
     
    		this.addActionInfo("ihm.message.dataExported");
    		//return SUCCESS;
    		return null;

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

Discussions similaires

  1. Réponses: 3
    Dernier message: 02/03/2012, 02h16
  2. [XL-2003] Problème pour renommer un fichier à partir d'une variable contenu dans une cellule
    Par the-geut dans le forum Macros et VBA Excel
    Réponses: 1
    Dernier message: 17/05/2010, 11h43
  3. [SERVLET]Appel d'un fichier à partir d'une servlet
    Par fchafia dans le forum Servlets/JSP
    Réponses: 5
    Dernier message: 17/03/2005, 12h21

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