I need to save an Image to my Desktop, but i cannot get that Image file, when I save it, I just save nothing, an empty file, I don't know how to get that file from FileItem.
for (FileItem lFileItem: c.emptyIfNull(pImageLogo))
{
long lFileSize = lFileItem.getSize();
String lFileName = lFileItem.getName();
String lExtensionFile = FilenameUtils.getExtension(lFileName);
String lContentType = lFileItem.getContentType();
if (lContentType.startsWith("image/")) {
if (lFileSize < 100 || lFileSize > Integer.valueOf(lLimitFileSize))
{
lShowAlert=c.msg("userReg.alertSizeFileErrorPart1","File size must be smaller than ") + Integer.valueOf(lLimitFileSize)/1000000 + c.msg("userReg.alertSizeFileErrorPart2","MB and greater than 1KB ");
throw new ErrorControl(lShowAlert);
break;
}
if (lFileSize<=0) break;
c.log(this, "file size="+lFileSize+" max allowed="+lLimitFileSize);
File lFile = new File(logoClientsFolder+"logo_"+ lIdClient + "." + lExtensionFile);
if(lFile.createNewFile())
{
System.out.println("File created: " + lFile.getName());
}
} else {
System.out.println("IS NOT AN IMAGE");
}
}
Can you help me please? Thanks!
you only create the File but don't write to it
you need something like:
final Path path = Paths.get(filename);
OutputStream outStream = Files.newOutputStream(path, StandardOpenOption.CREATE_NEW);
(add exception handling)
and then write the content to that outStream
and you should use NIO for file access, see:
Java: Path vs File
Related
Hey I'm trying to delete a image (file) but I can't :(
That how I upload the image:
try {
List<String> imagesPaths = new ArrayList<>();
for (String image : imagesBytes)
{
String base64Image = image.split(",")[1];
byte[] imageByte = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
String folder = "C:/images/" + LoggedInUser.UserId();
File newDirectory = new File(folder);
if (!newDirectory.exists())
{
newDirectory.mkdirs();
}
long timeMilli = new Date().getTime();
String imageType = image.substring("data:image/".length(), image.indexOf(";base64"));
String path = timeMilli + "." + imageType;
Files.write(Paths.get(folder, path), imageByte);
String newPath = LoggedInUser.UserId() + "/" + path;
imagesPaths.add(newPath);
}
logger.debug("uploadImages() in ImageService Ended by " + LoggedInUser.UserName());
return new ResponseEntity<>(imagesPaths, HttpStatus.OK);
} catch (Exception e) {
throw new ApiRequestException(e.getMessage());
}
And this how I delete it :
List<ImageJpa> images = imageRepository.findByStatus(Image.UNUSED.status);
System.out.println(images.size() + ": Images are not used");
images.forEach(image -> {
String imagePath = "C:/images/" + image.getPath();
System.out.println(imagePath);
File imagePathFile = new File(imagePath);
if (imagePathFile.exists())
{
boolean isDeleted = imagePathFile.delete();
if (isDeleted)
{
imageRepository.deleteById(image.getId());
System.out.println("Deleted the file: " + imagePathFile.getName());
} else {System.out.println("Failed to delete the file. :" + imagePathFile.getName());}
}else {
System.out.println("Already Deleted");
}
});
Always I got (Failed to delete the file ...)
Note : The image will deleted if I ReRender the the project again or close and open the IDE.
The problem was on other function :\
I was open the files after save it without CLOSE the connection after it !
This one what was messing on the read files
inputStream.close();
I want to upload a file from a struts action. I need in that action the path for my folder:
I tried using
String contextPath = request.getContextPath();
but I'm getting java.lang.NullPointerException
Either store in Catalina which is parent folder to your project folder
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "yourfolderName");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
java.util.Date date= new java.util.Date();
String Path = dir.getAbsolutePath() + File.separator + (new Timestamp(date.getTime())).toString().replace(":", "").toString().replace(".", ".").toString().replace(" ","").toString().replace("-","").toString()+".pdf";
Or make a folder in your project and store there.
if (!file.isEmpty()) {
//filter for checking file extewnsion
if(file.getContentType().equalsIgnoreCase("image/jpg") || file.getContentType().equalsIgnoreCase("image/jpeg")){
//if file is >2 MB or < 2MB
double size = file.getSize();
double kilobytes = (size / 1024);
double megabytes = (kilobytes / 1024);
if(megabytes<2){
try {
byte[] bytes = file.getBytes();
String filePath = request.getRealPath("/")+"yourFolderName\\ProfileImages\\"+SessionManagement.getUserName()+".jpg";
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(bytes);
stream.close();
//console call
}
else{
model.put("error", "Please select File less than 2 MB");
return new ModelAndView("uploadPhotoTile");
}
}else{
model.put("error", "Please select JPEG File");
return new ModelAndView("uploadPhotoTile");
}
} else {
model.put("error", "Please select File");
return new ModelAndView("uploadPhotoTile");
}
The code works as it has to until user inputs a filename with extension (.txt) and it already exists. So if the file "test.txt" exists and the user decides to name the new file as "test", it will be named as "test(1).txt", but if the user adds extension like "test.txt", the file will be named as "test.txt" and the next file user names "test.txt" will be saved as "test.txt(1).txt".
Is it possible to get the name of file from JFileChooser, remove it's extension if user input it and use it as name of the new file after adding number in the middle of original file name and it's extension? I can get name without extension as String type, but I need it as File type.
File ft = fc.getSelectedFile();
String ext = ".txt";
File tmp = new File(ft.getPath());
if (!fc.getSelectedFile().getAbsolutePath().endsWith(ext)){
ft = new File (ft + ext);
}
File test = new File(ft.getPath());
File temp = new File(ft.getPath());
File temp1 = new File(ft.getPath());
int count = 1;
while (temp.exists()) {
if(tmp.getAbsolutePath().endsWith(ext)){
}
File ft1 = new File (tmp + "(" + count + ")");
ft = new File (tmp + "(" + count + ")" + ext);
count++;
temp = new File(ft.getPath());
temp1 = new File(ft1.getPath());
}
if (!temp1.getAbsolutePath().endsWith(ext)){
ft = new File (temp1 + ext);
}
int cnt = count - 1;
if (!test.equals(temp)){
JOptionPane.showMessageDialog(null, "File already exists. So it's saved with (" + cnt + ") at the end.");
}
OK so I've tried to make this work without changing your code too much. Try this:
String filePath = fc.getSelectedFile().getAbsolutePath();
final String ext = ".txt";
String filePathWithoutExt;
if (filePath.endsWith(ext)) {
filePathWithoutExt = filePath.substring(0, filePath.length() - ext.length());
} else {
filePathWithoutExt = filePath;
}
File test = new File(filePathWithoutExt + ext);
File temp = new File(filePathWithoutExt + ext);
int count = 0;
while (temp.exists()) {
count++;
temp = new File(filePathWithoutExt + "(" + count + ")" + ext);
}
if (!test.equals(temp)) {
JOptionPane.showMessageDialog(null,
"File already exists. So it's saved with (" + count + ") at the end.");
}
EDIT:
By the recommendation of Marco N. it could be better to determine whether or not an extension exists by finding the last position of the . since this would also work with extensions other than ".txt". This value would then be used to split the string. The replacement code would look like this:
final int lastPeriodPos = filePath.lastIndexOf(".");
if (lastPeriodPos >= 0) {
filePathWithoutExt = filePath.substring(0, lastPeriodPos);
} else {
filePathWithoutExt = filePath;
However this would also have some issues if the user entered a file name that contained the . anywhere other than just before the file extension.
Hmm, I think this entry might be useful as well:
Remove filename extension in Java
I currently lack the time to properly test it (or better test it at all) but shouldn't it work this way:
public static String removeExtention(File f) {
String name = f.getName();
// Now we know it's a file - don't need to do any special hidden
// checking or contains() checking because of:
final int lastPeriodPos = name.lastIndexOf('.');
if (lastPeriodPos <= 0)
{
// No period after first character - return name as it was passed in
return f;
}
else
{
// Remove the last period and everything after it
File renamed = new File(f.getParent(), name.substring(0, lastPeriodPos));
return renamed;
}
}
I briefly tried to adjust the code from the posting mentioned above and it may very well contain some errors or flaws. (If you find some, do not hesitate to comment on them. Some of them might be due to my current lack of time, but I am always willing to learn and improve.) However I hope this may help you to find a proper solution to your problem.
I'm trying to zip a bunch of files using the Zip4j library. I pass a list of the file paths of the files I want to compress and I add them one by one into the zip file. For some reason, the last file does not get added. I checked the indexes of the loop and I'm pretty sure they're correct. I am not getting any exceptions or error messages. Here's my code:
// get the path; paths refers to the list of files to compress
String uuidString = UUID.randomUUID().toString();
String path = "H:/public/ZipFiles/" + uuidString + ".zip";
try {
// create the new zip file
ZipFile zipFile = new ZipFile(path);
File fileToAdd;
String message = "";
ZipParameters parameters = new ZipParameters();
// set compression method to store compression
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
// Set the compression level
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
// add each file to the zipFile
for(int i = 0; i < paths.size(); i++)
{
fileToAdd = new File(paths.get(i));
if(fileToAdd.exists())
{
System.out.println("writing file at " + paths.get(i) + " to the zip file");
zipFile.addFile(fileToAdd, parameters);
}
else
{
message += "File with at path " + paths.get(i) + " was not found.\n";
}
}
} catch (ZipException e) {
e.printStackTrace();
}
All the file paths get printed when they are added. Any ideas?
You're not closing the ZipFile.
I think there is a problem with the jar file from their own website at http://www.lingala.net/zip4j/download.php
But when I downloaded it from the maven repository at https://mvnrepository.com/artifact/net.lingala.zip4j/zip4j/1.3.2 , it is working perfectly.
I have written a Java web application that allows a user to download files from a server. These files are quite large and so are zipped together before download.
It works like this:
1. The user gets a list of files that match his/her criteria
2. If the user likes a file and wants to download he/she selects it by checking a checkbox
3. The user then clicks "download"
4. The files are then zipped and stored on a servera
5. The user this then presented with a page which contains a link to the downloadable zip filea
6. However on downloading the zip file the file that is downloaded is 0 bytes in sizea
I have checked the remote server and the zip file is being created properly, all that is left is to serve the file the user somehow, can you see where I might be going wrong, or suggest a better way to serve the zip file.
The code that creates the link is:
<%
String zipFileURL = (String) request.getAttribute("zipFileURL"); %>
<p>Zip File Link</p>
The code that creates the zipFileURL variable is:
public static String zipFiles(ArrayList<String> fileList, String contextRootPath) {
//time-stamping
Date date = new Date();
Timestamp timeStamp = new Timestamp(date.getTime());
Iterator fileListIterator = fileList.iterator();
String zipFileURL = "";
try {
String ZIP_LOC = contextRootPath + "WEB-INF" + SEP + "TempZipFiles" + SEP;
BufferedInputStream origin = null;
zipFileURL = ZIP_LOC
+ "FITS." + timeStamp.toString().replaceAll(":", ".").replaceAll(" ", ".") + ".zip";
FileOutputStream dest = new FileOutputStream(ZIP_LOC
+ "FITS." + timeStamp.toString().replaceAll(":", ".").replaceAll(" ", ".") + ".zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
// out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
while(fileListIterator.hasNext()) {
String fileName = (String) fileListIterator.next();
System.out.println("Adding: " + fileName);
FileInputStream fi = new FileInputStream(fileName);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(fileName);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return zipFileURL;
}
A URL cannot access any files (directly) under WEB-INF. I'd suggest using a servlet to return the file from whatever location it was saved to
Would also suggest saving the file outside the context of your webapp