Can't figure out why this keeps creating 2 folders? It makes a '0' folder and whatever the jobID is from the html. I want uploaded files in the jobID folder, not the '0' folder.
int userID = 1; // test
String coverLetter = "";
String status = "Review";
int jobID = 0;
String directoryName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart && request.getContentType() != null)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = null;
try
{
items = upload.parseRequest(request);
}
catch(FileUploadException e) {}
// Process the uploaded items
Iterator iter = items.iterator();
while(iter.hasNext())
{
FileItem item = (FileItem)iter.next();
if(item.isFormField())
{
if(item.getFieldName().equals("coverLetter"))
coverLetter = item.getString();
if(item.getFieldName().equals("jobID"))
jobID = Integer.parseInt(item.getString());
}
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";
File theDir = new File(directoryName);
if (!theDir.exists())
theDir.mkdir();
if(item.getFieldName().equals("file"))
{
File uploadedFile = new File(directoryName + item.getName());
try
{
item.write(uploadedFile);
}
catch(Exception e) {}
}
}
Edit:
Problem solved.I want uploaded files
It was because it was in the jobID folder, not the '0' folder.
I suspect this isn't true:
item.getFieldName().equals("jobID")
It's a bit difficult to guess though. Have you tried debugging in Eclipse (or similar)? Adding some logging might help too.
There must be 2 items parsed from the request, So perhaps you are sending 2 upload items.
The first item doesn't have the jobID FieldName so the directory name remain
.../Uploads/CV/0
So thats the time which is causing problems.
The second item does have the job ID so the directory gets created correctly.
Can you post the form so we can see, it may be something on there. Is the cover letter an additional file without jobId?
You could solve it by only creating dir if jobID exists.
Try printing/logging the jobID before the below line:
directoryName = request.getRealPath("/") + "/Uploads/CV/" + jobID + "/";
Related
I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.
You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}
Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!
You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";
I am uploading a file using Servlet using the code as follows::
FileItem fi = (FileItem) i.next();
String fileName = fi.getName();
out.print("FileName: " + fileName);
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
resumeflag = 1;
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(resumePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
What I am getting is my file is getting uploaded correctly. I needed to upload my file with different name, but make sure that file content should not be changed. Suppose I am having an image 'A.png' then it should be saved as 'B.png'. Please help guys?? I have tried like this:
File f1 = new File("B.png");
// Rename file (or directory)
file.renameTo(f1);
fi.write(file);
But not working
Assuming that you are referring to the Apache Commons FileItem you are simply in control what File instance you pass to FileItem.write. At that point, the File object is just an abstract name and the file will be created by that method.
It is your code which reads the name from the FileItem and constructs a File object with the same name. You don’t have to do it. So when you pass new File("B.png") to the write method of a FileItem representing an upload of A.png the contents will be save in a file B.png.
E.g. to do literally what you asked for you can change the line
fi.write(file);
to
if(file.getName().equals("A.png")) file=new File(file.getParentFile(), "B.png");
fi.write(file);
A simplified version of your code may look like:
String fileName = fi.getName();// name provided by uploader
if (fileName == null || fileName == "") {
resumefilepath = "";
} else {
// convert to simple name, i.e. remove any prepended path
fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar)+1);
// your substitution:
if(fileName.equalsIgnoreCase("A.png")) fileName="B.png";
// construct File object
file = new File(resumePath, fileName);
// and create/write the file
fi.write(file);
}
If you are looking for an answer where you can upload file and change name and insert it into database here it is
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = "/NVS_upload/NVS_school_facilities_img/";
String title=null,description=null,facility_id=null;
ArrayList<String> imagepath=new ArrayList<String>();
String completeimagepath=null;
// Verify the content type
String contentType = request.getContentType();
int verify=0;
//String school_id=null;
String exp_date=null;
String rel_date=null;
int school_id=0;
String title_hindi=null;
String description_hindi=null;
if ((contentType.indexOf("multipart/form-data") >= 0)) {
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:\\temp"));
// 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();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
//this genrates unique file name
String id = UUID.randomUUID().toString();
//we are splitting file name here such that we can get file name and extension differently
String[] fileNameSplits = fileName.split("\\.");
// extension is assumed to be the last part
int extensionIndex = fileNameSplits.length - 1;
// add extension to id
String newfilename= id + "." + fileNameSplits[extensionIndex];
//File newName = new File(filePath + "/" +);
//this stores the new file name to arraylist so that it cn be stored in database
imagepath.add(newfilename);
File uploadedFile = new File(filePath , newfilename);
fi.write(uploadedFile);
out.println("Uploaded Filename: " + filePath +
newfilename + "<br>");
}
else if (fi.isFormField()) {
if(fi.getFieldName().equals("title"))
{
title=fi.getString();
out.println(title);
}
if(fi.getFieldName().equals("description"))
{
description=fi.getString();
//out.println(description);
}
if(fi.getFieldName().equals("activity_name"))
{
facility_id=fi.getString();
//out.println(facility_id);
}
if(fi.getFieldName().equals("rel_date"))
{
rel_date=fi.getString();
//out.println(school_id);
}
if(fi.getFieldName().equals("exp_date"))
{
exp_date=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("school_id"))
{
school_id=Integer.valueOf(fi.getString());
// out.println(school_id);
}
if(fi.getFieldName().equals("title-hindi"))
{
title_hindi=fi.getString();
// out.println(school_id);
}
if(fi.getFieldName().equals("description-hindi"))
{
description_hindi=fi.getString();
out.println(school_id);
}
}
}
out.println("</body>");
out.println("</html>");
} catch(Exception ex) {
out.println(ex);
}
}
else {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>
<%
try{
completeimagepath=imagepath.get(0)+","+imagepath.get(1)+","+imagepath.get(2);
Connection conn = null;
Class.forName("org.postgresql.Driver").newInstance();
conn = DriverManager.getConnection(
"connection url");
PreparedStatement ps=conn.prepareStatement("INSERT INTO activities_upload (activity_name,title,description,pdfname,publish_date,expiry_date,title_hindi,description_hindi,school_id) VALUES(?,?,?,?,?,?,?,?,?)");
ps.setString(1,facility_id);
ps.setString(2,title);
ps.setString(3,description);
ps.setString(4,completeimagepath);
ps.setDate(5,java.sql.Date.valueOf(rel_date));
ps.setDate(6,java.sql.Date.valueOf(exp_date));
ps.setString(7,title_hindi);
ps.setString(8,description_hindi);
ps.setInt(9,school_id);
verify=ps.executeUpdate();
}
catch(Exception e){
out.println(e);
}
if(verify>0){
HttpSession session = request.getSession(true);
session.setAttribute("updated","true");
response.sendRedirect("activitiesform.jsp");
}
%>
Image upload working on localhost fine using request.getRealPath() but same we are using in server that's not
working, because server can not find specified path.. image can't be displayed .. how i can solved this problem.??
here is code for image uploading:
filePath =request.getRealPath("") + "\\img\\";
System.out.println(filePath);
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0))
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List fileItems = upload.parseRequest(request);
// message= fileItems.get(2).toString();
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if(fi.isFormField())
{
message=fi.getString();
System.out.println("message is : "+message);
bean.setEmp_id(Integer.parseInt(message));
}
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
System.out.println("field name"+fieldName);
fileName = fi.getName();
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\")));
} else {
file = new File(filePath
+ fileName.substring(fileName
.lastIndexOf("\\") + 1));
}
fi.write(file);
The getRealPath() gives the absolute path (on the file system) leading to a file specified in the parameters of the call. It returns the path in the format specific to the OS.
Read request#getRealPathfor its documentation.
Also it is advised to use servletRequest.getSession().getServletContext().getRealPath("/") instead of servletRequest.getRealPath("/") as it is deprecated.
so the best way is to provide the upload path for the server by yourself, as the method values specific to the OS the returned path may not be accessible(Permissions).
Hope this helps !!
Below is the code i have used to upload a file to the server. But the code throws a exception directory or file not found..
ResourceBundle rs_mail = ResourceBundle.getBundle("mail");
String upload_path = rs_mail.getString("upload_path");
File file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 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();
File uploadDir = new File(upload_path);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
file = new File(upload_path + file.separator + fi.getName());
fi.write(file);
}
Can any one point out the reason for the exception..
Contents of the property file
upload_path=../../../upload
Make sure you also create all the parent directories on the path to upload_path:
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
Note the use of mkdirs() instead of mkdir(). mkdir() will fail, if the parent structure does not exist. mkdirs() will also try to create the required parent directories.
You should also check for the return value, both methods will return false if the directory could not be created.
Actually I am trying to get no of files count to be uploading before uploading using common upload lib in jsp and I made a function for getting the counts of file this is here:
public static int getUploadFileCount(HttpServletRequest request) throws FileUploadException
{
int Result = 0;
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items)
{
if (!item.isFormField())
Result++;
}
return Result;
}
And use this function in business logic this here:
public void doChangeProfilePhoto(HttpServletRequest request) throws FileUploadException
{
if(UploadFileUtil.getUploadFileCount(request) != 1)
throw new FileUploadException("There is Multiple/None File upload for Profile Photo. ");
ProfileImage newProfileImage = new ProfileImage();
newProfileImage.setFileName("sam.jpg");
if(new UploadBPOProfilePhotoImpl().uploadPhoto(newProfileImage, request))
{}
}
And in this code after calling uploadPhoto function there is also use same code for retrieving the files one by one like this:
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) // Did not get file if i already used this code once For getting the files count:
{
if (!item.isFormField())
//did for makeing file and writing/saving it with a name
}
So here I get problem is that when I use this code its not get file when I have used the same code for counting the files
and if I comment this two line where I have use to get files count in doChangeProfilePhoto like this:
//if(UploadFileUtil.getUploadFileCount(request) != 1)
// throw new FileUploadException("There is Multiple/None File upload for Profile Photo. ");
Then its working. Why its happening that if one time it is used so after it unable to retrieving the file.What's the reason behind it
and is there any way to count files using common upload...and also for their names?