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");
}
%>
Related
I need to get the name of a CSV file selected for the user, but the getName() method does not return any value.
This is the code
private void readCSV(Uri uri) {
InputStream is;
File file = null;
try {
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't work
is = new FileInputStream(file);
Why does this not return the name of the file?
Edit 1
private void readCSV(Uri uri) {
InputStream is;
File file;
try {
/*This conditional is false*/
if (uri.getScheme().equals("file")) {
file = new File(uri.toString());
Log.i("File selected: ", file.getName()); //file.getName() doesn't
is = new FileInputStream(file);
} else {
/* this part is the one that runs */
is = this.getContentResolver().openInputStream(uri);
Log.i("File selected: ", uri.getLastPathSegment()); //i tried this, it returns me 5049 but it is not the name of the selected file
}
uri.toString() will return the object reference but not the file path.
You should call uri.getPath()
Use
new File(uri.getPath());
instead of
new File(uri.toString());
NOTE: uri.toString() returns a String in the format: "file:///mnt/sdcard/image.jpg", whereas uri.getPath() returns a String in the format: "/mnt/sdcard/image.jpg".
try this
fileName = uri.getLastPathSegment();
Getting file names through the apachecommons io lib https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FilenameUtils.html
String name = FileNameUtils.getName(uri.getPath());
I am using the code from the Google Drive API examples to insert a file in Drive which is failing with java.io.FileNotFoundException: document.txt (No such file or directory). I have commented out code that creates a folder in Drive and this works without any problems. So I am authenticated ok. Where am I going wrong.
Kind regards,
Ian.
public void saveToDrive(ServletContext sc){
GoogleCredential googleCredential = getGoogleApiCredential(sc);
Drive service = getDriveService(googleCredential);
String parentId = null;
try {
About about = service.about().get().execute();
System.out.println("Current user name: " + about.getName());
System.out.println("Root folder ID:" + about.getRootFolderId());
parentId = about.getRootFolderId();
System.out.println("Total quota (bytes): " + about.getQuotaBytesTotal());
System.out.println("Used quota (bytes): " + about.getQuotaBytesUsed());
}catch (IOException e){
}
File body = new File();
body.setTitle("Doc title");
body.setDescription("A toast document");
body.setMimeType("application/vnd.google-apps.file");
body.setParents(Arrays.asList(new ParentReference().setId(parentId)));
java.io.File fileContent = new java.io.File("document.txt");
FileContent mediaContent = new FileContent("plain/text", fileContent);
//File body = new File();
//body.setTitle("title");
//body.setMimeType("application/vnd.google-apps.folder");
try {
//File file = service.files().insert(body).execute();
File file = service.files().insert(body, mediaContent).execute();
logger.severe("File id: " + file.getId());
} catch (IOException e) {
logger.severe(e.toString());
}
}
I don't have time to completely re-run your scenario, but you may be able to test it with a method I use (so it is tested). The only obvious difference is that I stick THE SAME MIME TYPE in both 'body' and 'content'. Yours are different. Also I don't know what your 'about.getRootFolderId()' produces. You may try to stick "root" string there just to test it.
/**********************************************************************
* create file/folder in GOODrive
* #param prnId parent's ID, (null or "root") for root
* #param titl file name
* #param mime file mime type (optional)
* #param file file (with content) to create
* #return file id / null on fail
*/
static String create(String prnId, String titl, String mime, java.io.File file) {
String rsid = null;
if (mGOOSvc != null && titl != null && file != null) {
File meta = new File();
meta.setParents(Arrays.asList(new ParentReference().setId(prnId == null ? "root" : prnId)));
meta.setTitle(titl);
if (mime != null)
meta.setMimeType(mime);
File gFl = mGOOSvc.files().insert(meta, new FileContent(mime, file)).execute();
if (gFl != null && gFl.getId() != null)
rsid = gFl.getId();
}
return rsid;
}
It is taken from a working CRUD demo here.
Good Luck
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 !!
I have a method that get text from a JTextArea, create a file and write text on it as code below:
public void createTxt() {
TxtFilter txt = new TxtFilter();
JFileChooser fSave = new JFileChooser();
fSave.setFileFilter(txt);
int result = fSave.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION) {
File sFile = fSave.getSelectedFile();
FileFilter selectedFilter = fSave.getFileFilter();
String file_name = sFile.getName();
String file_path = sFile.getParent();
try{
if(!sFile.exists()) {
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "Warning file • " + file_name + " • created succesfully in \n" + file_path);
} else {
String message = "File • " + file_name + " • already exist in \n" + file_path + ":\n" + "Do you want to overwrite?";
String title = "Warning";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION){
sFile.delete();
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "File • " + file_name + " • overwritten succesfully in \n" + file_path);
}
}
}
catch(IOException e) {
System.out.println("Error");
}
}
}
and a txt file filter
public class TxtFilter extends FileFilter{
#Override
public boolean accept(File f){
return f.getName().toLowerCase().endsWith(".txt")||f.isDirectory();
}
#Override
public String getDescription(){
return "Text files (*.txt)";
}
}
The file filter for txt works fine but what I want is to add ".txt" extension when I type file name.
How to I have to modify my code?
I just use this
File fileToBeSaved = fileChooser.getSelectedFile();
if(!fileChooser.getSelectedFile().getAbsolutePath().endsWith(suffix)){
fileToBeSaved = new File(fileChooser.getSelectedFile() + suffix);
}
UPDATE
You pointed me out that the check for existing files doesn't work. I'm sorry, I didn't think of it when I suggested you to replace the BufferedWriter line.
Now, replace this:
File sFile = fSave.getSelectedFile();
with:
File sFile = new File(fSave.getSelectedFile()+".txt");
With this replacement, it isn't now needed to replace the line of BufferedWriter, adding .txt for the extension. Then, replace that line with the line in the code you posted (with BufferedWriter out = new BufferedWriter(new FileWriter(sFile)); instead of BufferedWriter out = new BufferedWriter(new FileWriter(sFile+".txt"));).
Now the program should work as expected.
I forgot to mention that you have to comment the line:
sFile.createNewFile();
In this way, you're creating an empty file, with the class File.
Just after this line, there is: BufferedWriter out = new BufferedWriter(new FileWriter(sFile));.
With this line, you are creating again the same file. The writing procedure is happening two times! I think it's useless to insert two instructions that are doing the same task.
Also, on the BufferedWriter constructor, you can append a string for the file name (it isn't possible on File constructor), that's the reason why I added +".txt" (the extension) to sFile.
This is a utility function from one of my programs that you can use instead of JFileChooser.getSelectedFile, to get the extension too.
/**
* Returns the selected file from a JFileChooser, including the extension from
* the file filter.
*/
public static File getSelectedFileWithExtension(JFileChooser c) {
File file = c.getSelectedFile();
if (c.getFileFilter() instanceof FileNameExtensionFilter) {
String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions();
String nameLower = file.getName().toLowerCase();
for (String ext : exts) { // check if it already has a valid extension
if (nameLower.endsWith('.' + ext.toLowerCase())) {
return file; // if yes, return as-is
}
}
// if not, append the first extension from the selected filter
file = new File(file.toString() + '.' + exts[0]);
}
return file;
}
I've done this function for this purpose :
/**
* Add extension to a file that doesn't have yet an extension
* this method is useful to automatically add an extension in the savefileDialog control
* #param file file to check
* #param ext extension to add
* #return file with extension (e.g. 'test.doc')
*/
private String addFileExtIfNecessary(String file,String ext) {
if(file.lastIndexOf('.') == -1)
file += ext;
return file;
}
Then you can use the function for example in this way :
JFileChooser fS = new JFileChooser();
String fileExt = ".txt";
addFileExtIfNecessary(fS.getSelectedFile().getName(),fileExt)
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 + "/";