简体   繁体   中英

Storing a file to server - java

I have searched for hours and tried many examples. None of which give me a result that remotely works. I am using eclipse scout and want to simply convert my binary resource from selecting a file to be stored in a directory. Here I have a button that when clicked it prompts you to select a file to upload (they will only be PDFs for now) and the result I get is a binary resource list. I have no idea how I can write that as an input stream. And if using input and output streams isn't the correct option I have not found a solution that allows me to chose a file and store it to C://FolderName/FileNameIChoose.

@Order(1750)
        public class UploadReceiptButton extends AbstractButton {
            @Override
            protected String getConfiguredLabel() {
                return TEXTS.get("UploadReceipt");
            }

            @Override
            protected void execClickAction() {
                FileChooser fc = new FileChooser(true);
                List<BinaryResource> data = fc.startChooser();
                System.out.println(data);
                //This is where the data from that file should be stored on my C drive as a file
            }
        }

The result of the data binary resource when selecting test.pdf is:

 [BinaryResource, content: 260502 bytes, filename: test.pdf, contentType: application/pdf, fingerprint: 1281876091]]

If anyone can point me in the right direction that would be extremally helpful to me and Im sure to a lot of others.

The BinaryResource object simply holds the content of the uploaded file in memory as byte[] array, along with some additional metadata such as the filename or the MIME content type. You can store or process it any way you like.

To write it to a file, you can either use a library (eg Apache Commons) or the standard Java file API. Scout also provides some helpful methods in their IOUtility to work with files.

FileChooser fc = new FileChooser(true);
List<BinaryResource> data = fc.startChooser();
data.forEach(br => {
  String filename = "C:/MyFolder/" + FileUtility.toValidFilename(br.getFilename());
  
  // Scout
  IOUtility.writeContent(filename, br.getContent());
  
  // Java File API (requires at least Java 7)
  try {
    Files.write(Paths.get(filename), br.getContent());
  }
  catch (IOException e) {
    throw BEANS.get(DefaultRuntimeExceptionTranslator.class).translate(e);
  }
});

Please be aware, that by doing this you are creating a file on the machine where the UI server is running ! This may be fine if your application is only used by a single user or is running on your local machine. Otherwise, you should store it in some kind of database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM