Reputation: 2153
First i must state that i'm jsp/servlet rookie trying to learn it's mechanisms.
INTRO:
Since i read this tutorial on using Apache-Commons-FileUpload 3.0, Servlet uploads .txt file successfully, and the file gets stored in Tomcat's wtpwebapps/MyProject/upload folder.
Here is the important part of UploadServlet's doPost method, it's just the same as in referenced tutorial:
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
// saves the file on disk
item.write(storeFile);
}
}
request.setAttribute("message", "Upload has been done successfully!");
} catch (Exception ex) {
request.setAttribute("message", "There was an error: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
At the end of code segment, programmer specifies message text that will be printed in /messages.jsp file.
QUESTION:
Before setting the request attribute, how can i obtain an uploaded file as stream, do something with it line by line (using BufferedReader or similar), close the stream and send it as... String[] for example, to /message.jsp via container's request object?
Upvotes: 0
Views: 2028
Reputation: 692063
FileItem
has a getInputStream()
method. Call it, read the file using the returned input stream, fill a List<String>
with its contents, and add the list as an attribute to the request.
Upvotes: 1