0

I am stuck in uploading byte array using apache common vfs, below is the example uploading file using filepath, I googled but I am not getting the solution for file upload using byte array

    public static boolean upload(String localFilePath, String remoteFilePath) {
    boolean result = false;
    File file = new File(localFilePath);
    if (!file.exists())
        throw new RuntimeException("Error. Local file not found");

    try (StandardFileSystemManager manager = new StandardFileSystemManager();
            // Create local file object
            FileObject localFile = manager.resolveFile(file.getAbsolutePath());

            // Create remote file object
            FileObject remoteFile = manager.resolveFile(
                    createConnectionString(hostName, username, password, remoteFilePath),
                    createDefaultOptions());) {

        manager.init();

        // Copy local file to sftp server
        remoteFile .copyFrom(localFile, Selectors.SELECT_SELF);
        result = true;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

The above example it took from here

and it is working fine.

Below is the code for uploading byte array using FTPSClient

 private boolean uploadFtp(FTPSClient ftpsClient, byte[] fileData, String fileName) {

 boolean completed = false;
 byte[] bytesIn = new byte[4096];
 try (InputStream inputStream = new ByteArrayInputStream(fileData); OutputStream outputStream =
  ftpsClient.storeFileStream(fileName);) {
  int read = 0;

  while ((read = inputStream.read(bytesIn)) != -1) {
   outputStream.write(bytesIn, 0, read);
  }

  completed = ftpsClient.completePendingCommand();
  if (completed) {
   logger.info("File uploaded successfully societyId");
  }

 } catch (IOException e) {
 logger.error("Error while uploading file to ftp server", e);
 }

 return completed;
}
pise
  • 849
  • 6
  • 24
  • 51
  • What makes you believe that [Apache Commons VFS](https://commons.apache.org/proper/commons-vfs/) supports HTTP Form POST with Content-Type `multipart/form-data`? None of the [listed File Systems](https://commons.apache.org/proper/commons-vfs/filesystems.html) claim to support that. – Andreas Sep 21 '19 at 19:54
  • @Andreas then I have to use old FTPSClient only to upload multiplepartfile only? – pise Sep 21 '19 at 20:01
  • The FTPS is a "SSL" secure FTP protocol, not an HTTP protocol. I think you're confused about what "multipart" means. It specifies a format for an **HTTP POST** request to include binary file data. HTTP != FTP. If you're attempting to ask how to upload files to a server using Apache Commons VFS, then it depends on which protocols the server supports. Since we don't know that, we can't answer that, but FTP, FTPS, SFTP, and WebDAV seems to be your choices. – Andreas Sep 21 '19 at 20:04
  • 1
    @Andreas, sorry for writing multipartfile instead of byte array, I have written code which is working for uploading byte array using FTPSClient the same I want to achieve using apache VFS. I have changed the question and content. – pise Sep 21 '19 at 20:23

2 Answers2

2

This is an old question, but I was having the same problem and I was able to solve it without assuming a local file, e.g. using a ByteArrayInputStream, so this may be useful for someone having the same problem as pise. Basically, we can copy an input stream directly into the output stream of the remote file.

The code is this:

InputStream is = ... // you only need an input stream, no local file, e.g. ByteArrayInputStream
    
DefaultFileSystemManager fsmanager = (DefaultFileSystemManager) VFS.getManager();
        
FileSystemOptions opts = new FileSystemOptions();
FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
StaticUserAuthenticator auth = new StaticUserAuthenticator(host, username, password);
         
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
        
String ftpurl = "ftp://" + host + ":" + port + "/" + folder + "/" + filename;
FileObject remoteFile = fsmanager.resolveFile(ftpurl, opts);
        
try (OutputStream ostream = remoteFile.getContent().getOutputStream()) {
    // either copy input stream manually or with IOUtils.copy()
    IOUtils.copy(is, ostream);
}
        
boolean success = remoteFile.exists();
long size = remoteFile.getContent().getSize();
System.out.println(success ? "Successful, copied " + size + " bytes" : "Failed");
Edu
  • 160
  • 10
1

See e.g. Example 6 on https://www.programcreek.com/java-api-examples/?api=org.apache.commons.vfs.FileContent:

/**
 * Write the byte array to the given file.
 *
 * @param file The file to write to
 * @param data The data array
 * @throws IOException
 */

public static void writeData(FileObject file, byte[] data)
        throws IOException {
    OutputStream out = null;
    try {
        FileContent content = file.getContent();
        out = content.getOutputStream();
        out.write(data);
    } finally {
        close(out);
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247