Multiple file Upload [duplicate] - java

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 :

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.

avoid duplication while uploading file on server [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
I want to avoid duplication while uploading file. If a file is updated then eventhough it has same name as which was uploaded previously, I should be able to upload that file on server.
I have written following servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("from").equals("upload")) {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(req)) {
PrintWriter writer = resp.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// constructs the directory path to store upload file
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// creates the directory if it does not exist
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(req);
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();
filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
System.out.println(f.format(storeFile.lastModified()));
System.out.println(storeFile.lastModified());
System.out.println(f.parse(f.format(storeFile.lastModified())));
File[] files = new File(
"C:\\bootcamp\\programs\\eclipse-jee-neon-RC3-win32-x86_64\\eclipse\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\excelFileManagement\\upload")
.listFiles();
int uploadFiles=0;
for (File file : files) {
if (fileName.equals(file.getName())) {
uploadFiles =1;
System.out.println("same");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd hh:mm:sss");
String currentFile = df.format(storeFile.lastModified());
String storedFile = df.format(file.lastModified());
System.out.println("currentFile" + currentFile + "storedFile" + storedFile);
if (currentFile.contains(storedFile)) {
System.out.println("Same file cannot be uploaded again");
getServletContext().getRequestDispatcher("/Error.jsp").forward(req, resp);
} else {
// saves the file on disk
item.write(storeFile);
System.out.println("Upload has been done successfully!");
// Reading excel file
ReadingExcelFile rd = new ReadingExcelFile();
rd.readExcel(filePath);
getServletC
ontext().getRequestDispatcher("/DisplayTables.jsp").forward(req, resp);
}
}
}
catch (Exception ex) {
System.out.println("There was an error: " + ex.getMessage());
}}
However, I am getting same last modified date and time for both the files. And if a new file is uploaded storeFile.lastModified() returns Thu Jan 01 05:30:00 IST 1970 value
Can you confirm what is actual lastModified date of the file already uploaded by OS explorer ?
Second thing in SimpleDateFormat constructor arg m stands for minutes and M stands for month.Also S stands for millsecond.So your correct code would be
SimpleDateFormat("yyyy-MM-dd hh:mm:S")
Can you try with these changes and check ?

java - how to get file type in servlet 3.0 [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
I have written a servlet using servlet3.0 for uploading the file and it uploads the file very well. But I want to save the file in the server in the format it is uploaded by the client.
Part filePart = request.getPart("chosenFile");
String filename = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
System.out.println(filePart.getContentType().split("/")[1]);
InputStream inputStream =null;
OutputStream outputStream =null;
File fileSaveDirectory = new File(UPLOAD_DIR);
if(!fileSaveDirectory.exists()){
fileSaveDirectory.mkdir();
}
String content_path = UPLOAD_DIR+File.separator+filename;//earlier
//here I was appending the string ".pdf" to every file
//but now I want the file type to be the uploaded file type.
//say if user uploads in .jpeg or any other.
System.out.println("Content Path : "+content_path);
outputStream = new FileOutputStream(new File(content_path));
inputStream = filePart.getInputStream();
int read=0;
while((read=inputStream.read())!=-1){
outputStream.write(read);
}
if(outputStream!=null)
outputStream.close();
if(inputStream !=null)
inputStream.close();
How to keep the file type , the type of uploaded file. Please help !!!
See # http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html:
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
So, when your (file upload) request is setup well/normal, the (http) header content-disposition will contain (among others, separated by ;) a filename attribute, which you can use (in the whole or) to extract the file suffix.

Failed to read the uploaded file using inputstream jsp

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?

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