2

Can we create FileItem object from given file name and file location using Java? If we use commons-fileupload jar we can upload file using jsp/html and in servlet on parsing request we will get List<FileItem>. But I want to do file upload using plain java where I want to create FileItem object manually (I don't want to use byte[] array to store the file). So is there any way to create FileItem object manually?

icza
  • 389,944
  • 63
  • 907
  • 827
CodeName007
  • 51
  • 1
  • 1
  • 6
  • This guys answer was complete. https://stackoverflow.com/questions/4120635/java-lang-nullpointerexception-while-creating-diskfileitem – Mike Croteau Dec 21 '20 at 02:49

1 Answers1

1

Yes, you can.

Use the DiskFileItemFactory like this:

DiskFileItemFactory factory = new DiskFileItemFactory();
FileItem fi = factory.createItem("formFieldName", "application/zip", false,
    "/var/temp/somefile.zip");

Obviously use content type and other parameters appropriate to your case.

icza
  • 389,944
  • 63
  • 907
  • 827
  • DiskFileItemFactory factory = new DiskFileItemFactory(); FileItem fi = factory.createItem("formFieldName", "application/zip", false,pathToLoad); File fileLoc=new File(pathToLoad); factory.setRepository(fileLoc); try { File file=new File file=new File(pathToLoad+File.separator+fileName); fi.write(file); – CodeName007 Jul 16 '14 at 10:20
  • 4
    java.lang.NullPointerException at org.apache.commons.fileupload.disk.DiskFileItem.isInMemory(DiskFileItem.java:275) at org.apache.commons.fileupload.disk.DiskFileItem.write(DiskFileItem.java:391) – CodeName007 Jul 16 '14 at 10:21
  • I am getting this problem when i am creating FileItem manually – CodeName007 Jul 16 '14 at 10:22