0

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!

  • How far did you get? What's your output? – jiveturkey Apr 02 '20 at 11:23
  • But how can I get the content of the file if I get it from an input type file, and browsers doesn't let you obtain the real path of the file. –  Apr 02 '20 at 13:44

1 Answers1

0

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

mamayr
  • 31
  • 4
  • But how can I get the content of a FileItem? Because I get that from an input type file, but I cannot get the real path, browsers don't let it. –  Apr 02 '20 at 13:31
  • never worked with it, but according to https://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/FileItem.html a get() returns the content as byte[] – mamayr Apr 02 '20 at 14:36