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.
Related
I am trying to write a bitmap to any of the usual internal folders like 'Pictures, Documents, Download' etc. Below is the file creation I am doing
String root = Environment.getRootDirectory().toString();
File myDir = new File(root + File.separator + Environment.DIRECTORY_PICTURES);
String Filename = "pic.png";
File fl = new File(myDir + File.separator + Filename);
FileOutputStream out = new FileOutputStream(fl);
At the last line, it throws an exception which says 'No such File/Directory'.
If I check fl.canWrite(), it says false!, i.e. fl is not writable.
I even tried to give 'Unrestricted Access' in my testing mobile for this App.
What could be the problem?
What kind of additional things I need to do?
Edit: When I toast, myDir is shown as /system/Pictures. When I go to File Manager in phone, under my 'Phone storage', 'Pictures' folder is there. That's a usual folder in Android right ?
you should use
\\...
File myDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
\\...
then do a check to confirm directory exist and then proceed to write your file.
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.
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 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) {
...
}
I have Successfully created folder and uploaded file in Document and Media Library.
I am storing File Name in DB and based on that file name I want to fetch that specific file from Document Library. I am new to Liferay.
I am fetching all Files saved in Document & Media Library using this Code Snippet. But is there any way to directly fetch File using File Name.
Here is my Code Snippet
public void getAllDLFileLink(ThemeDisplay themeDisplay,String folderName){
try {
Folder folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(themeDisplay.getScopeGroupId(), folder.getFolderId());
for (DLFileEntry file : dlFileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
System.out.println("DL Link=>"+url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
As your code snippet already finds the URL for a DLFileEntry, I'm assuming that you want to get hold of the binary content. Check DLFileEntry.getContentStream().
If this assumption is wrong and you want to embed the image in the HTML output of your portlet, use the URL within an <img src="URL-HERE"/> tag
You can use DLFileEntryLocalServiceUtil.getFileEntry(long groupId, long folderId, java.lang.String title) to get file using file name / title, as following:
String fileName = "abc.jpg";
Folder folder = DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntry(
themeDisplay.getScopeGroupId(), folder.getFolderId(), fileName);
However, title is stored with extension, therefore, you will require to pass complete name of image / file.