salut,
comment faire pour uploader un fichier du client au serveur en utilisant une servlet?
merci .
[Modéré par Didier] : ajout de tag dans le titre - Les règles du forum Java
salut,
comment faire pour uploader un fichier du client au serveur en utilisant une servlet?
merci .
[Modéré par Didier] : ajout de tag dans le titre - Les règles du forum Java
comme ca sans connaitre tout tes besoin je dirai soit un mail avec le fichier en piece jointe, ou bien des sockets !!!
par contr il faudra que ton serveur soi en ecoute permanente avec cette solution...
Pour uploader un fichier, tu utilises un formulaire défini comme suit :
dans lequel tu utilises un input de type file.
Code : Sélectionner tout - Visualiser dans une fenêtre à part <FORM method="post" name="uploadForm" enctype="multipart/form-data" action=" ">
Du côté de ton servlet, il existe des apis pour récupérer ton fichier et tous les paramêtres de ton formulaire.
Personnelement je te recommande l'api de Jakarta Commons FileUpload : http://jakarta.apache.org/commons/fileupload/ .
Elle est simple d'utilisation et bien documentée.
Bonjour,
serait-il possible d'avoir un exemple complet?
Je dois charger un fichier de l'utilisateur vers mon serveur.
J'ai peu de temps devant moi pour fouiller donc ça pourrait m'aider bcp.
Bon ben je progresse.
Voilà ou j'en suis :
doGet je charge une fichier index.html
Dans index.html j'ai :
L'objectif est de transmettre un fichier .xml et de le parser avec la méthode en fin de code.
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 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <FORM method="post" name="uploadForm" enctype="multipart/form-data" action="SurveyAnswersScriptalImport"> <input name="fichier" type="file" size="50" maxlength="100000" accept="text/plain"> <input type="submit" name="uploadForm" value="Envoyer"> </FORM> </body> </html>
Sauf que là, je sais pas faire.
J'essaye de récupérer le paramétre "fichier" qui apparemment serait une String...
et du coup j'essaye dans bienrecu.jsp d'afficher cette String qui apparemment est null (ou alors je me suis planté pour passer fichier en attribut dans bien reçu).
Le contenu de bienrecu.jsp :
Le code de ma servlet (ce qui est important se situe au niveau du doGet et du doPost) :
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 <%@ page import="intermed.survey.*" import="javax.servlet.*" import="java.io.IOException" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <servlet:defineObjects/> <% String _file = (String)request.getAttribute("_file"); %> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <span>Bien reçu <%= _file %> </span> </body> </html>
Please Help!
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 package intermed.survey; import java.io.IOException; import java.rmi.RemoteException; import java.util.Iterator; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import localhost.axis.services.interviewee.Interviewee; import localhost.axis.services.interviewee.IntervieweeService; import localhost.axis.services.interviewee.IntervieweeServiceLocator; import org.jdom.Document; import org.jdom.Element; /** * Servlet implementation class SurveyAnswersScriptalImport */ public class SurveyAnswersScriptalImport extends HttpServlet { private static final long serialVersionUID = 1L; IntervieweeService _serviceDoc = new IntervieweeServiceLocator(); Interviewee _port_interviewee; /** * @see HttpServlet#HttpServlet() */ public SurveyAnswersScriptalImport() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //PrintWriter _out = response.getWriter(); response.setContentType("text/html"); RequestDispatcher _srd = this.getServletContext().getRequestDispatcher(response.encodeURL("/WEB-INF/jsp/index.jsp")); _srd.include(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String _file = request.getParameter("fichier"); request.setAttribute("_file", _file); response.setContentType("text/html"); RequestDispatcher _srd = this.getServletContext().getRequestDispatcher(response.encodeURL("/WEB-INF/jsp/bienrecu.jsp")); _srd.include(request, response); } public void parseXMLScriptalAnswers(Document _xmlScriptal , String _id_user) { int _id_survey = -1; Element _racine = _xmlScriptal.getRootElement(); List _osdatas = _racine.getChildren("OSDATA"); Iterator _osdata_it = _osdatas.iterator(); while(_osdata_it.hasNext()) { Element _osdata = (Element)_osdata_it.next(); //peut ressembler à "id-survey-1-id-question-1-id-pa-4" ou à "id-survey-1-id-question-1" String _osdata_name = _osdata.getAttribute("name").getValue(); String _osdata_value = _osdata.getAttribute("value").getValue(); String _osdata_date = _osdata.getAttribute("lastStrokeDateTime").getValue(); if(!_osdata_name.contains("id-pa")) //c'est une réponse à une question libre { _id_survey = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-survey-") + "id-survey-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-survey-") + "id-survey-".length()))); int _id_question = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-question-") + "id-question-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-question-") + "id-question-".length()))); System.out.println("[SurveyAnswersScriptal] id_survey : " + _id_survey + " id_question : " + _id_question); try { this._port_interviewee.postFreeAnswer(_id_user, _id_question, _osdata_value); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { _id_survey = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-survey-") + "id-survey-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-survey-") + "id-survey-".length()))); int _id_question = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-question-") + "id-question-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-question-") + "id-question-".length()))); int _id_pa = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-pa-") + "id-pa-".length() , _osdata_name.length())); System.out.println("[SurveyAnswersScriptal] id_survey : " + _id_survey + " id_question : " + _id_question + " id_pa : " + _id_pa); //déterminer le type de question try { if(this._port_interviewee.isCheckQuestion(_id_question)) { if(Integer.parseInt(_osdata_value)==1) this._port_interviewee.postCheckAnswer(_id_user, _id_question, _id_pa); else this._port_interviewee.postUnCheckAnswer(_id_user, _id_question, _id_pa); } else if(this._port_interviewee.isOrdoQuestion(_id_question)) { this._port_interviewee.postOrdoAnswer(_id_user, _id_question, _id_pa, Integer.parseInt(_osdata_value)); } else if(this._port_interviewee.isRadioQuestion(_id_question)) { if(Integer.parseInt(_osdata_value)==1) this._port_interviewee.postRadioAnswer(_id_user, _id_question, _id_pa); else this._port_interviewee.postUnCheckAnswer(_id_user, _id_question, _id_pa); } else if(this._port_interviewee.isValueQuestion(_id_question)) { this._port_interviewee.postValueAnswer(_id_user, _id_question, _id_pa, _osdata_value); } } catch (RemoteException e) { // TODO Auto-generated catch block System.out.println("[SurveyAnswerScriptal] WS not responding"); e.printStackTrace(); } } } try { this._port_interviewee.validateSurvey(_id_user, _id_survey); } catch (RemoteException e) { // TODO Auto-generated catch block System.out.println("[SurveyAnswerScriptal] WS not responding"); e.printStackTrace(); } } }
Que fais-je de mal...
Salut,
Ton paramétre fichier n'est pas un string... plutôt un 'multipart/form-data'. Il faut utiliser la procédure d'exemple du Upload pour comprendre : Commons FileUpload
J'ai obtenu ce code là (qui est en prod) :
L'ensemble est dans une JSP, et les fichier envoyés sont placés dans un répertoire temporaire : .\tmp\ -qui est dans la racine de l'application.
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 <%@page import="org.apache.commons.fileupload.*" %> <%@page import="org.apache.commons.io.*" %> <%@page import="java.util.List, java.io.File, java.util.Iterator" %> [...] boolean isMultipart = FileUpload.isMultipartContent(request); if(!isMultipart){ request.setAttribute("message", "Request was not multipart!"); request.getRequestDispatcher("userIndex.jsp").forward(request, response); return; } DiskFileUpload upload = new DiskFileUpload(); List items = upload.parseRequest(request); Iterator itr = items.iterator(); while(itr.hasNext()){ FileItem item = (FileItem) itr.next(); if(!item.isFormField()) { File fullFile = new File(item.getName()); String path=getServletContext().getRealPath("/")+"tmp/"; File savedFile = new File(path,fullFile.getName()); item.write(savedFile); } }
Merci.
Je n'avais pas posté mais j'ai fini par trouver une solution.
Donc j'ai récupéré la lib fileupload (commons-fileupload-1.2.1.jar)
Dans index.jsp, j'ai un formulaire en POST avec un textarea et un champ d"'upload de fichier.
Je teste si la réponse est multipart dans le doPost:
Je crée les un FileItemFactory et un ServletFileUpload :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart) request.setAttribute("multipart", "yes"); else request.setAttribute("multipart", "no");
Je parse l'upload :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5 // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory);
Je process les items (iterateur puis test sur chaque item, si il vient d'un champ de fromulaire, c'est le textarea sinon c'est le fichier uploadé) :
Code : Sélectionner tout - Visualiser dans une fenêtre à part List items = upload.parseRequest(request);
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 // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { _user_name = item.getString(); } else { fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); InputStream uploadedStream = item.getInputStream();
Je poste ici mon code.
Servlet.java (l'essentiel est dan le doPost):
index.jsp :
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209 package intermed.survey; import java.io.IOException; import java.io.InputStream; import java.rmi.RemoteException; import java.util.Iterator; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.rpc.ServiceException; import localhost.axis.services.interviewee.Interviewee; import localhost.axis.services.interviewee.IntervieweeService; import localhost.axis.services.interviewee.IntervieweeServiceLocator; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; /** * Servlet implementation class SurveyAnswersScriptalImport */ public class SurveyAnswersScriptalImport extends HttpServlet { private static final long serialVersionUID = 1L; IntervieweeService _serviceDoc = new IntervieweeServiceLocator(); Interviewee _port_interviewee; /** * @see HttpServlet#HttpServlet() */ public SurveyAnswersScriptalImport() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //PrintWriter _out = response.getWriter(); response.setContentType("text/html"); RequestDispatcher _srd = this.getServletContext().getRequestDispatcher(response.encodeURL("/WEB-INF/jsp/index.jsp")); _srd.include(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ 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) request.setAttribute("multipart", "yes"); else request.setAttribute("multipart", "no"); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request String _user_name =""; String fileName =""; try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { _user_name = item.getString(); } else { fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); InputStream uploadedStream = item.getInputStream(); SAXBuilder sxb = new SAXBuilder(); try { Document _xml = sxb.build(uploadedStream); try { this.parseXMLScriptalAnswers(_xml, _user_name); } catch (ServiceException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } // = new Document(new StringReader(uploadedStream.toString())); uploadedStream.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("_user_name", _user_name); request.setAttribute("_fileName", fileName); response.setContentType("text/html"); RequestDispatcher _srd = this.getServletContext().getRequestDispatcher(response.encodeURL("/WEB-INF/jsp/bienrecu.jsp")); _srd.include(request, response); } public void parseXMLScriptalAnswers(Document _xmlScriptal , String _id_user) throws ServiceException { this._port_interviewee = this._serviceDoc.getinterviewee(); int _id_survey = -1; Element _racine = _xmlScriptal.getRootElement(); List _osdatas = _racine.getChildren("OSDATA"); Iterator _osdata_it = _osdatas.iterator(); while(_osdata_it.hasNext()) { Element _osdata = (Element)_osdata_it.next(); //peut ressembler à "id-survey-1-id-question-1-id-pa-4" ou à "id-survey-1-id-question-1" String _osdata_name = _osdata.getAttribute("name").getValue(); System.out.println("[Servlet parseXMLScriptalAnswers] _osdata_name : "+ _osdata_name); String _osdata_value = _osdata.getAttribute("value").getValue(); String _osdata_date = _osdata.getAttribute("lastStrokeDateTime").getValue(); if(!_osdata_name.contains("id-pa")) //c'est une réponse à une question libre { _id_survey = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-survey-") + "id-survey-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-survey-") + "id-survey-".length()))); int _id_question = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-question-") + "id-question-".length() , _osdata_name.length())); System.out.println("[SurveyAnswersScriptal] id_survey : " + _id_survey + " id_question : " + _id_question); try { this._port_interviewee.postFreeAnswer(_id_user, _id_question, _osdata_value); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { _id_survey = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-survey-") + "id-survey-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-survey-") + "id-survey-".length()))); //_id_survey = Integer.parseInt(_osdata_name.substring(9,11)); int _id_question = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-question-") + "id-question-".length() , _osdata_name.indexOf("-", _osdata_name.indexOf("id-question-") + "id-question-".length()))); int _id_pa = Integer.parseInt( _osdata_name.substring(_osdata_name.indexOf("id-pa-") + "id-pa-".length() , _osdata_name.length())); System.out.println("[SurveyAnswersScriptal] id_survey : " + _id_survey + " id_question : " + _id_question + " id_pa : " + _id_pa); //déterminer le type de question try { if(this._port_interviewee.isCheckQuestion(_id_question)) { if(Integer.parseInt(_osdata_value)==1) this._port_interviewee.postCheckAnswer(_id_user, _id_question, _id_pa); else { System.out.println("[SurveyAnswersScriptal] id_user : " + _id_user + " id_question : " + _id_question + " id_pa : " + _id_pa); this._port_interviewee.postUnCheckAnswer(_id_user, _id_question, _id_pa); } } else if(this._port_interviewee.isOrdoQuestion(_id_question)) { this._port_interviewee.postOrdoAnswer(_id_user, _id_question, _id_pa, Integer.parseInt(_osdata_value)); } else if(this._port_interviewee.isRadioQuestion(_id_question)) { if(Integer.parseInt(_osdata_value)==1) this._port_interviewee.postRadioAnswer(_id_user, _id_question, _id_pa); else this._port_interviewee.postUnCheckAnswer(_id_user, _id_question, _id_pa); } else if(this._port_interviewee.isValueQuestion(_id_question)) { this._port_interviewee.postValueAnswer(_id_user, _id_question, _id_pa, _osdata_value); } } catch (RemoteException e) { // TODO Auto-generated catch block System.out.println("[SurveyAnswerScriptal] WS not responding"); e.printStackTrace(); } } } try { this._port_interviewee.validateSurvey(_id_user, _id_survey); } catch (RemoteException e) { // TODO Auto-generated catch block System.out.println("[SurveyAnswerScriptal] WS not responding"); e.printStackTrace(); } } }
bienrecu.jsp :
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 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <FORM method="post" name="uploadForm" enctype="multipart/form-data" action="SurveyAnswersScriptalImport"> <input type="text" name="user_name"> <input name="fichier" type="file" size="50" maxlength="100000" accept="text/plain"> <input type="submit" value="Envoyer"> </FORM> </body> </html>
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 <%@ page import="intermed.survey.*" import="javax.servlet.*" import="java.io.IOException" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <servlet:defineObjects/> <% String _user_name = (String)request.getAttribute("_user_name"); String _fileName = (String)request.getAttribute("_fileName"); %> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <span>L'utilisateur <%=_user_name %> a uploadé le fichier <%=_fileName %> </span> </body> </html>
Vous avez un bloqueur de publicités installé.
Le Club Developpez.com n'affiche que des publicités IT, discrètes et non intrusives.
Afin que nous puissions continuer à vous fournir gratuitement du contenu de qualité, merci de nous soutenir en désactivant votre bloqueur de publicités sur Developpez.com.
Partager