Failed to read the uploaded file using inputstream jsp - java

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?

Related

In email attachment any type of document file is sent with File extension instead of coreect extension

I am fetching S3 objects and then sending the object in email as an attachment. I am saving the contents in a temporary file. For images the code is working fine but in case of documents (pdf, docx, csv) files the attachments are sent without extension so they are not accessible.
try {
fullObject = s3Client.getObject(new GetObjectRequest(bucketName, key));
System.out.println("fullObject: " + fullObject);
ObjectMetadata metadata = fullObject.getObjectMetadata();
System.out.println(" meta data type: " + metadata.getContentType());
InputStream inputStream = fullObject.getObjectContent();
String extension = fullObject.getKey();
int index = extension.lastIndexOf('.');
if(index > 0) {
extension = extension.substring(index + 1);
System.out.println("File extension is " + extension);
}
File file = File.createTempFile(key, "."+ extension );
System.out.println("file: "+ file);
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(inputStream, outputStream);
} catch (Exception e) {
System.out.println("error in copying data from one file to another");
}
dataSource = new FileDataSource(file);
System.out.println("added datasource in the list");
attachmentsList.add(dataSource);
}
Upon going through this code, I got to know that the issue was not in this code but when I was setting the name of the File. I was setting filename without any extension, for example I set Filename as "temporary" this caused the documents to be saved with tmp extension. All I had to do was add the extension of the object with its name ("temporary.docx"), this solved the issue and attachments were sent properly and were accessible.

java.io.FileNotFoundException (No such file or directory) - Download File

I have Web Application hosted on Linux, contains page to upload .rar file and another page to download it. for upload function working fine and file uploaded successfully to server but for download it gives me below exception:
[servelt.scriptdownloadservelt] in context with path [/OSS-CPE-Tracker] threw exception
java.io.FileNotFoundException: \usr\local\apache-tomcat-8.5.31\OSS-CPE-Tracker\Zaky\QCAM.rar (No such file or directory)
I used below funcation to make upload:
String destDir = "/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky";
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
if(name.equalsIgnoreCase("QCAM.rar")) {
File destFile = new File(destDir, "QCAM.rar");
if (destFile.exists()) {
destFile.delete();
}
item.write(new File("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky" + File.separator + name));
request.setAttribute("gurumessage", "File Uploaded Successfully");
}else {
request.setAttribute("gurumessage", "Kindly use the agreed name");
}
and here function for download that i face issue on it and above exception appear:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String gurufile = "QCAM.rar\\";
String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ gurufile + "\"");
FileInputStream fileInputStream = new FileInputStream(gurupath
+ gurufile);
int i;
while ((i = fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
The only reason for this error is that file cannot be found under that path.
Please verify the path
String gurufile = "QCAM.rar\\";
String gurupath = "\\usr\\local\\apache-tomcat-8.5.31\\OSS-CPE-Tracker\\Zaky";
// <...>
FileInputStream fileInputStream = new FileInputStream(gurupath
+ gurufile);
In unix systems file path is resolved using forward slash / and not a backslash \.
Try changing to the same value as your upload script:
FileInputStream fileInputStream = new FileInputStream("/usr/local/apache-tomcat-8.5.31/OSS-CPE-Tracker/Zaky/QCAM.rar")
That should do

File Streaming using Java similar to node.js

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();

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();

Categories

Resources