Reputation: 101
I know that maybe it can be a duplicated question, i read similar post on internet, but i cannot send my input value from jsp to servlet. I can upload file but i need to send an input value. Servlet:
try {
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);
out.println("--------------");
out.println("fileName = " + fileName);
out.println("Kind = " + fileNameWithOutExt);
out.println("field name = " + fieldName);
out.println("contentType = " + contentType);
String fileContents = null;
try {
fileContents = IOUtils.toString(in);
out.println("lenght: " + fileContents.length());
String[] content = fileContents.split("\n");
String[] property = content[0].split(",");
out.println("lunghezza " + property.length);
for (String propr : property) {
out.println("prop: " + propr);
}
//out.println(Arrays.toString(property));
//out.println(fileContents);
} finally {
IOUtils.closeQuietly(in);
}
}
}
} catch (SizeLimitExceededException e) {
out.println("You exceeded the maximu size ("
+ e.getPermittedSize() + ") of the file ("
+ e.getActualSize() + ")");
}
} catch (Exception ex) {
throw new ServletException(ex);
}
}
And that's my jsp
<form action="/upload_kind" method="post" enctype="multipart/form-data" >
<input type="file" name="file" size="50" />
<input type="text" name="namespace" id="namespace">
<br />
<input type="submit" value="Upload File" />
</form>
I read about a "item.getString()" method but it's in DiskFileItem class and not in FileItemStream, so i can see that "namespace" is sent, but i cannot see its value. Thx and sorry for my bad english
Upvotes: 0
Views: 4682
Reputation: 101
Following the duplicated link, i was able to resolve my problem. I used this code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldName = item.getFieldName();
String fieldValue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldName = item.getFieldName();
String fileName = FilenameUtils.getName(item.getName());
InputStream fileContent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
Upvotes: 1