I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.
Related
I want to upload image, and return filepath to save in database so i can later diplay that image.
I am using Primefaces UploadeFile. But when i try to upload file, i get file not found Exception. I am propably making error in path, but i don't know where those files are saved.
I have method that performs file upload.
Essentialy i generate unique file name and try to copy it to location.
Date date = new Date();
String filename = author.getSlug() + "-" + date.getTime() + "." + FilenameUtils.getExtension(image.getFileName());
File path = new File("/uploads/authors", filename);
InputStream input = image.getInputstream();
Files.copy(input, path.toPath(), StandardCopyOption.REPLACE_EXISTING);
This code throws file not found exception.
I am facing a problem but have not able to solve it yet. Let me share what I have done till now. I tried to delete a file using java.nio.file packages. And below is my code.
// directory will be dynamically generated.
String directory = fileDirectory+ "//" + fileName;
Path path = Paths.get(directory);
if (Files.exists(path)) {
Files.delete(path);
}
I generated the path correctly. But when Files.exists(path) calls it return false. That's why file is not deleted. But if I generated the directory string by hard-coded than it works perfectly.
// hard-coded directory works perfectly.
String directory = "C://opt//tomcat//webapps//resources//images//sprite.jpg";
I also tried the another method Files.deleteIfExists(path);. Which check the both the file existence and delete the file.
The other packages org.apache.commons.io.FileUtils and java.io.File have tried. But can't resolve the issue.
Note: My application is in spring-boot. And I read the directory from the application.properties file for both save images and delete images.
EDIT:
file uploading I mean save into the directory is perfectly worked. But file deletion does not work.
application.properties
image.root.dir=images
image.root.save.dir=C:/opt/tomcat/webapps/resources/
in implementation file
#Value("${image.root.dir}")
private String UPLOADED_FOLDER;
#Value("${image.root.save.dir}")
private String saveDir;
String directory = saveDir + UPLOADED_FOLDER + "/" + fileName;
save file into directory
String directory = saveDir + UPLOADED_FOLDER + "/";
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(directory);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
path = Paths.get(directory, file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
logger.error("save image into directory : " + e);
}
String directory = fileDirectory+ "//" + fileName;
This is not the correct separator used between a directory and a file name, though it seems to work as well.
This means the problem is not the separator, but a mismatch between the code that you use to generate the path and this code. You're generating the directory into somewhere else than where this is pointing.
I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}
I have a JFilechooser to select a filename and path to store some data. But I also want to store an additional file in the same path, same name but different extension. So:
File file = filechooser.getSelectedFile();
String path = file.getParent();
String filename1 = file.getName();
// Check the extension .ext1 has been added, else add it
if(!filename1.endswith(".ext1")){
filename2 = filename1 + ".ext2";
filename1 += ".ext1";
}
else{
filename2 = filename1;
filename2 = filename2.substring(0, filename2.length-4) + "ext2";
}
// And now, if I want the full path for these files:
System.out.println(path); // E.g. prints "/home/test" withtout the ending slash
System.out.println(path + filename1); // E.g. prints "/home/testfilename1.ext1"
Of course I could add the "/" in the middle of the two strings, but I want it to be platform independent, and in Windows it should be "\" (even if a Windows path file C:\users\test/filename1.ext1 would probably work).
I can think of many dirty ways of doing this which would make the python developer I'm carrying inside cry, but which one would be the most clean and fancy one?
You can use the constants in the File class:
File.separator // e.g. / or \
File.pathSeparator // e.g. : or ;
or for your path + filename1 you can do
File file = new File(path, filename1);
System.out.println(file);
Just use the File class:
System.out.println(new File(file.getParent(), "filename1"));
You can use:
System.getProperty("file.separator");
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.