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 ?
Related
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
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 :
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();
These are days that I'm banging my head on this problem and maybe you that certainly know more than me you can help me ....
Then I try to explain better.
I have a javascript file that through the library d3.js builds the html code pages and replaces it with the other code each part a different function ... The page will not charge (Ajax).
At some point I need to allow the user to upload an image to their profile picture so I make sure that the html code bait
<input type="file" id="file">
and a
<input type = "button" onclick = "javaScript: performAjaxSubmit ()">
PerformAjaxSubmit function () sends the data to a Java Servlet via a xmlHttpRequest level 2, which, from what I understand, can send not only strings but also more complex things such as files.
The function is as follows:
function performAjaxSubmit() {
var sampleFile = document.getElementById("file").files[0];
var formdata = new FormData();
formdata.append("sampleFile", sampleFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:8080/Prova/Upload", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
alert(this.responseText);
}
};
}
The code in the Servlet instead is this:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
System.out.println(request.getAttribute("username"));
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
filePath="C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti";
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +"/"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
System.out.println(filePath +
fileName.substring(fileName.lastIndexOf("\\")+1));
file = new File( filePath +"/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}
Now (sorry if the question is a bit long) it works but the problem is that the images are saved in the path that I have provided me with the command:
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
How do I then save it remotely? That is, once I load the site of such Altrevista, how do I make sure that they are not piĆ saved to C but in a folder in your project?
I hope I explained. I'm using Apache Tomcat v7.0.
Thanks in advance!
You can use ServletContext.getRealPath
This code returns <context root>/upload (depends on your deployment configuration)
request.getSession().getServletContext().getRealPath("/upload")