getServletContext().getRealPath("/") omitting forward slash (/) - java

I'm trying to upload a file from an HTML file input.
I am using Apache Commons FileUpload and the file uploads successfully. However, when I try storing the file path in my MySQL, it is storing it without file path code:
String uploadFolder = getServletContext().getRealPath("/");
String fileName = new File(item.getName()).getName();
filePath = uploadFolder+"/"+fileName;
File uploadedFile = new File(filePath);
This is how I'm trying to store the file.
sample filepath stored
C:UsersLashDesktopworkspace3.metadata.pluginsorg.eclipse.wst.server.core mp0wtpwebappsJavaECom/download doget.txt

I have no idea what this question is about, but the correct way to do the operations your posted code is doing is as follows:
File uploadFolder = new File(getServletContext().getRealPath("/"));
String fileName = new File(item.getName()).getName(); // not sure what's going on here
File uploadedFile = new File(uploadFolder, fileName);

Related

How to rename a file before insert to a path Java?

I need to insert a file to a path. However, the file name need to change to a specific name before inserted.
How can I change the name of the file before insert to path? As many resources online only able to change the file name after inserted. Online Resource for rename file
My code currently
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + file.getOriginalFilename();
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
//I think need to rename the file here before insert to path
byte[] bytes = file.getBytes();
Path path = Paths.get(finalPath);
Files.write(path, bytes);
Replace your code with this and update your "CustomName_ABC" with your new fileName.
String localPath = "c://Users/foody/Documents/write_file_local/";
String finalPath = localPath + "CustomName_ABC";
File uploadPath = new File(finalPath);
if (!uploadPath.getParentFile().exists()) {
uploadPath.getParentFile().mkdirs();
}
Files.copy(file.toPath(), uploadPath.toPath());
You can copy your old file to a new filePath (directory) by using Files.copy() method. It will take two parameters:
Old file path
New file path

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

How to store uploaded mulitple pdf file to a specific location in java?

i want to store uploaded file in a specific location in java. if i upload a.pdf then i want it to store this at "/home/rahul/doc/upload/". i went through some questions and answers of stack overflow but i am not satisfied with solutions.
i am working with Play Framework 2.1.2. i am not working with servlet.
i am uploading but it is storing file into temp directory but i want that file store into a folder as not a temp file i want that file like a.pdf in folder not like temp file.
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
FilePart filePart1 = body.getFile("filePart1");
File newFile1 = new File("path in computer");
File file1 = filePart1.getFile();
InputStream isFile1 = new FileInputStream(file1);
byte[] byteFile1 = IOUtils.toByteArray(isFile1);
FileUtils.writeByteArrayToFile(newFile1, byteFile1);
isFile1.close();
}
but i am not satisfied with this solution and i am uploading multiple doc files.
for eg. i upload one doc ab.docx then after upload it is storing temp directory and file is this:
and it's location is this: /tmp/multipartBody5886394566842144137asTemporaryFile
but i want this: /upload/ab.docx
tell me some solution to fix this.
Everything's correct as a last step you need to renameTo the temporary file into your upload folder, you don't need to play around the streams it's as simple as:
public static Result upload() {
Http.MultipartFormData body = request().body().asMultipartFormData();
FilePart upload = body.getFile("picture");
if (upload != null) {
String targetPath = "/your/target/upload-dir/" + upload.getFilename();
upload.getFile().renameTo(new File(targetPath));
return ok("File saved in " + targetPath);
} else {
return badRequest("Something Wrong");
}
}
BTW you should implement some checking if targetPath doesn't exist to prevent errors and/or overwrites. Typical approach is incrementing the file name if file with the same name already exists, for an example sending a.pdf three times should save the files as a.pdf, a_01.pdf, a_02.pdf, etc.
i just completed it. My solution is working fine.
My solution of uploading multiple files is :
public static Result up() throws IOException{
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles=body.getFiles();
InputStream input;
OutputStream output;
File part1;
String prefix,suffix;
for (FilePart picture:resourceFiles) {
part1 =picture.getFile();
input= new FileInputStream(part1);
prefix = FilenameUtils.getBaseName(picture.getFilename());
suffix = FilenameUtils.getExtension(picture.getFilename());
part1=new File("/home/rahul/Documents/upload",prefix+"."+suffix);
part1.createNewFile();
output = new FileOutputStream(part1);
IOUtils.copy(input, output);
Logger.info("Uploaded file successfully saved in " + part1.getAbsolutePath());
}

Get file size in Java from relative path to file

How can I get file size in Java if I have a relative path to a file such as:
String s = "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with two diferent strings:
String[] separatedPath = s.split("/");
List<String> wordList = Arrays.asList(separatedPath);
String ret = "/" + wordList.get(1) + "/" + wordList.get(2) + "/" + wordList.get(3)+ "/" + wordList.get(4);
s = ret;
In this case s="/documents/19/21704/file2.pdf";
In second case s="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with:
File file1 = new File(s);
long filesize = file1.length();
and with:
String filePath = new File(s).toURI().getPath();
File file2 = new File(filePath);
long filesize2 = file1.length();
and also with (if the problem is in not providing full path):
String absolutePath = FileUtil.getAbsolutePath(file1);
File file3 = new File(absolutePath);
long filesize3 = file3.length();
byte[] bytes1=FileUtil.getBytes(file1);
byte[] bytes2=FileUtil.getBytes(file2);
byte[] bytes3=FileUtil.getBytes(file3);
I am always getting in debug that filesizes in all cases are 0.
Maybe is worth noticing that the three attributes of file1 and file2 and file3 are always:
filePath: which is always null;
path: "/documents/19/21704/liferay-portlet-development.pdf"
prefixLength: 1
Since I am also using Liferay I also tried their utility.
long compId = article.getCompanyId();
long contentLength = DLStoreUtil.getFileSize(compId, CompanyConstants.SYSTEM, s);
I also should notice that in my .xhtml view I can access the file with:
<a target="_blank"
href="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc">
file2.pdf
</a>
Pdf opens in a new window. So it is stored on my server.
What am I doing wrong here? That I cant get the file size from bean?
Any answer would be greatly appreciated.
What am I doing wrong here?
In Java, you can use the File.length() method to get the file size in bytes.
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
}
System.out.println("bytes : " + bytes);
The problem is that your "relative" path is expressed as an absolute path (begining with "/", which is read as FS root).
A relative file path should look like:
documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
./documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
Or, you could get your application root folder File and compose the absolute path:
File rootFolder =new File("path to your app root folder");
File myfile=new File(rootFolder, "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc");

url = new java.net.URL()

url = new java.net.URL(s) doesn't work for me.
I have a string C:\apache-tomcat-6.0.29\webapps\XEPServlet\files\m1.fo and need to make a link and give it to my formatter for output, but malformed url recieved. It seems that it doesn't make my string to url.
I want also mention, that file m1.fo file is in files folder, in my webapp\product\, and I gave the full path to string like: getServletContext().getRealPath("files/m1.fo"). What I am doing wrong? How can I recieve the url link?
It is possible to get an URL from a file path with the java.io.File API :
String path = "C:\\apache-tomcat-6.0.29\\webapps\\XEPServlet\\files\\m1.fo";
File f = new File(path);
URL url = f.toURI().toURL();
Try: file:///C:/apache-tomcat-6.0.29/webapps/XEPServlet/files/m1.fo
It isn't preferable to write file:/// . Indeed it works on windows system,but in unix - there were problems.
Instead of using
myReq.put("xml", new String []{"file:" + System.getProperty("file.separator") +
getServletContext().getRealPath(DESTINATION_DIR_PATH) +
System.getProperty("file.separator") + xmlfile});
you can write
myReq.put("xml", new String [] {getUploadedFileURL (xmlfile)} );
, where
public String getUploadedFileURL(String filename) {
java.io.File filePath = new java.io.File(new
java.io.File(getServletContext().getRealPath(DESTINATION_DIR_PATH)),
filename);
return filePath.toURI().toURL().toString();
A file system path is not a URL. A URL is going to need a protocol prefix for one. To reference file system use "file:" in front of your path.

Categories

Resources