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();
Related
I was going over a nodejs tutorial which mentioned that Node.JS does not keep the file in memory when writes files to a disk and it flushes chunks of file to disk as and when it receives it. Is Java capable of handling file in a similar fashion or does it keep the entire file in memory before flushing to disk? In the past , I have faced out of memory exception when I tried to upload files using servlets.
The answer is Yes, In java you can use streaming APIs that can help you do it.
try the following guide to understand it better :
http://commons.apache.org/proper/commons-fileupload/streaming.html
Example :
Fileupload using Servlet:
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
ow we are ready to parse the request into its constituent items. Here's how we do it:
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
// Process the input stream
...
}
}
And at last you can write the input stream in a file using the follwing approach :
FileOutputStream fout= new FileOutputStream ( yourPathtowriteto );
BufferedOutputStream bout= new BufferedOutputStream (fout);
BufferedInputStream bin= new BufferedInputStream(stream);
int byte;
while ((byte=bin.read()) != -1)
{
bout.write(byte_);
}
bout.close();
bin.close();
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.
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 :
I am trying to upload a file from jsp page. I am successful to get all the fields from the jsp file but can able to read the file which i get uploaded in the jsp. I am uploading a zip file from the jsp page. here is my code.
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
FileItemStream item = iter.next();
if (!item.isFormField()) {
String name = item.getFieldName();
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
InputStream stream = item.openStream();
BuildVO buildVO = buildDAO.findByFileName(item.getName());
ZipEntry entry;
ZipInputStream zis = new ZipInputStream(stream);
while ((entry = zis.getNextEntry()) != null ) {
System.out.println(buildVO.getOriginalFileName()+">>>>>>>>>>>>>>>>>>>>fileFound??????"+entry.getName());
}
}
}
with this code i get the input stream of a uploaded file. But from that i cannot able to read the zip file and it contents.Any one can help me?
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