How to upload a file in Tomcat5.5? - java

I want to do the following in tomcat 5.5
1. upload a excel file
2. process the file based on some crieteria
3. show the result
I am able to do all from 2 to 3 but not able to upload a file in tomcat 5.5 and could not also find example.
Pleaes help me.

Maybe you could give a try on Apache commons fileUpload
You can get an sample here
A more hands-on with not so much conceptual and clarification things could be found here.
On your Servlet you will just use something like:
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

Apache has provided an API for uploading a file. You can try this.
http://commons.apache.org/fileupload/using.html

Use Apache’s Commons FileUpload and HttpClient.
Here some links to help you out.
http://www.theserverside.com/news/1365153/HttpClient-and-FileUpload
http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache
https://stackoverflow.com/a/2424824/1438132

Related

Java get part of muiltipart form

I have a formular in which there are 4 files that I need to upload.
Because I'm using OpenCms which automaticly uploads all files in a Folder i don't need to do that for my own.
The Problem now: I need an enctype="multipart/form-data" Formular, so the Software can upload it.
Now I can't read my Parameters with request.getParameter("") instead I'm using a List of FileItems and an Iterator.
But the List<FileItems> I get returns [].
Maybe you can help me with that Problem. Here's the Part of my Code:
private void createNachricht(CmsObject cms, HttpServletRequest request) {
System.out.println("execute createNachricht...");
List<CmsProperty> bildprops = new ArrayList<CmsProperty>();
List<CmsProperty> props = new ArrayList<CmsProperty>();
Map<String, String> allRequestData = new TreeMap<String, String>();
try {
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("isMultipartContent");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(
factory);
#SuppressWarnings("unchecked")
List<FileItem> fileItemsList = servletFileUpload
.parseRequest(request); // returns [] so it's empty...
Iterator<FileItem> it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = it.next();
if (!fileItemTemp.isFormField()) {
StringBuilder fileName = new StringBuilder(
sanitizeFilename(fileItemTemp.getName()));
System.out.println("fileName: " + fileName);
} else {
String name = fileItemTemp.getFieldName();
String val = fileItemTemp.getString("utf-8");
allRequestData.put(name, val);
System.out.println("name: " + name);
System.out.println("value: " + val);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
// more code here...
}
Files arrive in request stream that can be read once. I guess your CMS has already read this request stream, so it's now empty and ServletFileUpload can read nothing from it.
Ask your CMS for files. Refer to your CMS docs about how to get multi-part parameters that are parsed alongside uploaded files.

Multiple file Upload [duplicate]

This question already has answers here:
Upload multiple files at once to a Struts2 #Action
(2 answers)
Closed 7 years ago.
How to upload multiple file in any location. My Problem is that i am selecting multiple files but when i click on the upload button only last one file is uploaded with rename name and the rename name is all file name append with comma like this (file1,file2,flie3)
Here is the code
File saveFile = null;
String tempPath = System.getProperty("java.io.tmpdir");
saveFile = new File(tempPath + File.separator + fileUploadFileName);
FileUtils.copyFile(fileUpload, saveFile);
By using Apache commons fileupload FileItem, the sample code will be like this
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());
ex.printStackTrace();
}
Download MultipleFilesUpload.zip from Multi File Upload. Refer to this Upload for more details :

Reading MultipartContent from a POST request [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to upload files to server using JSP/Servlet?
I'm implementing a fileupload servlet that is used alongside resumable.js
Everytime I try to read a file, I either get a NoSuchElement exception or a NumberFormatException with a string inside the file I'm reading. I'm sure I made a hiccup somewhere, but can't seem to tell
Here's a snippet of what I use to read request and write to file
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(temp_dir));
ServletFileUpload upload = new ServletFileUpload(factory);
Iterator<FileItem> iter = upload.parseRequest(request).iterator();
FileItem item = iter.next();
OutputStream out;
try {
out = new FileOutputStream(new File(dest_dir));
IOUtils.copy(item.getInputStream(), out);
logger.debug("Wrote file " + resumableIdentifier + " with chunk number "
+ resumableChunkNumber + " to " + temp_dir);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
Did I do something wrong that is making the code actually read and interpret the contents of the file?
You have to iterate over the FileItems.
Right after this line:
Iterator<FileItem> iter = upload.parseRequest(request).iterator();
You should have something like this:
File dir = new File(dest_dir);
if (!dir.isDirectory()) dir.mkdirs();
while(iter.hasNext()) {
FileItem item = iter.next();
Also do not forget to close the output stream for every file item.
out = new FileOutputStream(new File(dir, item.getName()));
IOUtils.copy(item.getInputStream(), out);
out.close();

Upload file from jsp

I am trying to upload multiple files from jsp using below code:
When I execute it from my local machine I am able to upload in the local systems folder.
But when I access the same from remote machine I am expecting that the files should be uploaded to the same machine where my tomcat exist ,but I get error C:\Files\`folder/file not found`.
Please guide.How to upload it in remote machine or where the tomcat resides
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
} else {
try {
String itemName = item.getName();
File savedFile = new File("C:\\Files\\a.tiff");
item.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This is the path where I want to upload all files C:\\Files\\ of the machine where tomcat is.
Change your file save path to new File("C:\\Files\\"); . Even, still you have any problem, then create one folder with Files name in another drive E or F whatever and change your code like new File("E:\\Files\\"); if you wanna save your file to E drive.
Note: Since, C drive is the primary drive in windows OS, so due to lack of permission, it won't allow to create new file/folder in that drive. So, please try the alternative solution. I mean try to change your file location.
you need to change this new File("C:\\Files\\"); to a foldername on my your remote-server
please take a look at this article
http://www.avajava.com/tutorials/lessons/how-do-i-monitor-the-progress-of-a-file-upload-to-a-servlet.html?page=2
http://www.tutorialspoint.com/jsp/jsp_file_uploading.htm
http://www.caucho.com/resin-3.0/jsp/tutorial/multipart.xtp
http://www.c-sharpcorner.com/UploadFile/0d4935/how-to-upload-files-in-jsp/

Commons File Upload Not Working In Servlet

I have a servlet which is meant to handle the upload of a very large file. I am trying to use commons fileupload to handle it. Currently, the file I am attempting to upload is 287MB.
I set up the FileItemFactory and ServletFileUpload, then set a very large max file size on the ServletFileUpload.
Unfortunately, when I attempt to create a FileItemIterator, nothing happens. The form is set with the correct action, multipart encoding, and for the POST method.
Can anyone assist? doPost() of the servlet is posted below:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ensure that the form is multipart encoded since we are uploading a file
if (!ServletFileUpload.isMultipartContent(req)) {
//throw new FileUploadException("Request was not multipart");
log.debug("Request was not multipart. Returning from call");
}
// create a list to hold all of the files
List<File> fileList = new ArrayList<File>();
try {
// setup the factories and file upload stuff
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(999999999);
// create a file item iterator to cycle through all of the files in the req. There SHOULD only be one, though
FileItemIterator iterator = upload.getItemIterator(req);
// iterate through the file items and create a file item stream to output the file
while (iterator.hasNext()) {
// get the file item stream from the iterator
FileItemStream fileItemStream = iterator.next();
// Use the Special InputStream type, passing it the stream and the length of the file
InputStream inputStream = new UploadProgressInputStream(fileItemStream.openStream(), req.getContentLength());
// create a File from the file name
String fileName = fileItemStream.getName(); // this only returns the filename, not the full path
File file = new File(tempDirectory, fileName);
// add the file to the list
fileList.add(file);
// Use commons-io Streams to copy from the inputstrea to a brand-new file
Streams.copy(inputStream, new FileOutputStream(file), true);
// close the inputstream
inputStream.close();
}
} catch (FileUploadException e) {
e.printStackTrace();
}
// now that we've save the file, we can process it.
if (fileList.size() == 0) {
log.debug("No File in the file list. returning.");
return;
}
for (File file : fileList) {
String fileName = file.getName();
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
List<Feature> featureList = new ArrayList<Feature>(); // arraylist may not be the best choice since I don't know how many features I'm importing
while (!line.isEmpty()) {
String[] splitLine = line.split("|");
Feature feature = new Feature();
feature.setId(Integer.parseInt(splitLine[0]));
feature.setName(splitLine[1]);
feature.setFeatureClass(splitLine[2]);
feature.setLat(Double.parseDouble(splitLine[9]));
feature.setLng(Double.parseDouble(splitLine[10]));
featureList.add(feature);
line = reader.readLine();
}
file.delete(); // todo: check this to ensure it won't blow up the code since we're iterating in a for each
reader.close(); // todo: need this in a finally block somewhere to ensure this always happens.
try {
featureService.persistList(featureList);
} catch (ServiceException e) {
log.debug("Caught Service Exception in FeatureUploadService.", e);
}
}
}
It was an incredibly stupid problem. I left the name attribute off of the FileUpload entry in the GWT UiBinder. Thanks for all of the help from everyone.
Are the only request parameters available File items? Because you may want to put in a check:
if (!fileItemStream.isFormField()){
// then process as file
otherwise you'll get errors. On the surface of things your code looks fine: no errors in the Tomcat logs?
You need to add enctype='multipart/form-data' in html form

Categories

Resources