Skip to content

Latest commit

 

History

History
605 lines (464 loc) · 22.8 KB

files.md

File metadata and controls

605 lines (464 loc) · 22.8 KB

Files

File objects represent individual files in Box. They can be used to download a file's contents, upload new versions, and perform other common file operations (move, copy, delete, etc.).

Get a File's Information

Calling getInfo() on a file returns a snapshot of the file's info.

BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();

Requesting information for only the fields you need with [getInfo(String...)] get-info2 can improve performance and reduce the size of the network request.

BoxFile file = new BoxFile(api, "id");
// Only get information about a few specific fields.
BoxFile.Info info = file.getInfo("size", "owned_by");

Update a File's Information

Updating a file's information is done by creating a new [BoxFile.Info] box-file-info object or updating an existing one, and then calling updateInfo(BoxFile.Info).

BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.new Info();
info.setName("New Name");
file.updateInfo(info);

Download a File

A file can be downloaded by calling download(OutputStream) and providing an OutputStream where the file's contents will be written.

BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();

FileOutputStream stream = new FileOutputStream(info.getName());
file.download(stream);
stream.close();

Download progress can be tracked by providing a ProgressListener to download(OutputStream, ProgressListener). The ProgressListener will then receive progress updates as the download completes.

BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();

FileOutputStream stream = new FileOutputStream(info.getName());
// Provide a ProgressListener to monitor the progress of the download.
file.download(stream, new ProgressListener() {
    public void onProgressChanged(long numBytes, long totalBytes) {
        double percentComplete = numBytes / totalBytes;
    }
});
stream.close();

Upload a File

Files are uploaded to a folder by calling the uploadFile(InputStream, String) method.

BoxFolder rootFolder = BoxFolder.getRootFolder(api);
FileInputStream stream = new FileInputStream("My File.txt");
BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt");
stream.close();

Upload progress can be tracked by providing the size of the file and a ProgressListener to uploadFile(InputStream, String, long, ProgressListener). The ProgressListener will then receive progress updates as the upload completes.

BoxFolder rootFolder = BoxFolder.getRootFolder(api);
FileInputStream stream = new FileInputStream("My File.txt");
BoxFile.Info newFileInfo = rootFolder.uploadFile(stream, "My File.txt", 1024, new ProgressListener() {
    public void onProgressChanged(long numBytes, long totalBytes) {
        double percentComplete = numBytes / totalBytes;
    }
});
stream.close();

Upload a large File in chunks

An upload session can be created with the createUploadSession(fileName, fileSize) method to upload a large file in chunks.

//Create the upload session
BoxFile file = new BoxFile(api, "id");
BoxFileUploadSession.Info sessionInfo = file.createUploadSession("My_Large_File.txt", fileSize);

//Get the session resource from the session info
BoxFileUploadSession session = sessionInfo.getResource();

//Create the Message Digest for the whole file
MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException ae) {
    throw new BoxAPIException("Digest algorithm not found", ae);
}

Once the upload session is created, using that session the large file can be uploaded in chuncks with the uploadPart(partId, stream, offset, partSize, totalSizeOfFile) method of the session instance. If there is a failure in uploading any of the parts, the failed part can be uploaded again without affecting the other parts.

//Reading a large file
FileInputStream fis = new FileInputStream("My_Large_File.txt");
//Create the digest input stream to calculate the digest for the whole file.
DigestInputStream dis = new DigestInputStream(fis, digest);

List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>();

//Get the part size. Each uploaded part should match the part size returned as part of the upload session.
//The last part of the file can be less than part size if the remaining bytes of the last part is less than
//the given part size
long partSize = sessionInfo.getPartSize();
//Start byte of the part
long offset = 0;
//Overall of bytes processed so far
long processed = 0;
while (processed < fileSize) {
    long diff = fileSize - processed;
    //The size last part of the file can be lesser than the part size.
    if (diff < partSize) {
        partSize = diff;
    }

    //Generate a unique partId
    String partId = LargeFileUpload.generateHex();
    //Upload a part. It can be uploaded asynchorously
    BoxFileUploadSessionPart part = session.uploadPart(partId, dis, offset, partSize, fileSize);
    parts.add(part);

    //Increase the offset and proceesed bytes to calculate the Content-Range header.
    processed += partSize;
    offset += partSize;
}

At any point in time, the list of parts that are being uploaded successfully can be retrivied with the listParts(offset, limit) method of the session instance.

//The following snippet retrives first 1000 parts that are uploaded. Both can be modified based on the needs.
BoxFileUploadSessionPartList partList = session.listParts(0, 1000);
List<BoxFileUploadSessionPart> parts = partList.getEntries();

Once all the parts are uploaded successfully. the upload sessiion can be commited with the commit(digest, parts, attributes, ifMatch, ifNoneMatch) method.

//Creates the file hash
byte[] digestBytes = digest.digest();
//Base64 encoding of the hash
String digestStr = Base64.encode(digestBytes);

//Commit the upload session. If there is a failure, abort the commit.
BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null);

The upload session can be aborted at any time with the abort() method of the session instance.

session.abort();

The upload session status can be retrived at any time with the getstatus() method. This call will update the parts processed and other information in the session info instance.

BoxFileUploadSession.Info updatedSessionInfo = session.getStatus();

Create a large File

A large file can be uploaded with the uploadLargeFile(InputStream, fileName, fileSize) method.

File myFile = new File("My Large_File.txt"); 
FileInputStream stream = new FileInputStream(myFile);

BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile.Info fileInfo = rootFolder.uploadLargeFile(inputStream, "My_Large_File.txt", myFile.length());

Copy a File

A file can be copied to a new folder and optionally be renamed with the copy(BoxFolder) and copy(BoxFolder, String) methods.

BoxFolder rootFolder = BoxFolder.getRootFolder(api);
BoxFile file = new BoxFile(api, "id");
BoxFile.Info copiedFileInfo = file.copy(rootFolder, "New Name");

Delete a File

Calling the delete() method will move the file to the user's trash.

BoxFile file = new BoxFile(api, "id");
file.delete();

Get Previous Versions of a File

For users with premium accounts, versions of a file can be retrieved with the getVersions() method.

BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
for (BoxFileVersion version : versions) {
    System.out.format("SHA1 of \"%s\": %s\n", item.getName(), version.getSha1());
}

Upload a New Version of a File

New versions of a file can be uploaded with the uploadVersion(InputStream) method.

BoxFile file = new BoxFile(api, "id");
FileInputStream stream = new FileInputStream("My File.txt");
file.uploadVersion(stream);

Download a Previous Version of a File

For users with premium accounts, previous versions of a file can be downloaded by calling download(OutputStream).

BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);

FileOutputStream stream = new FileOutputStream(firstVersion.getName());
firstVersion.download(stream);
stream.close();

Promote a Previous Version of a File

A previous version of a file can be promoted with the promote() method to become the current version of the file.

BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);
firstVersion.promote();

Delete a Previous Version of a File

A version of a file can be deleted and moved to the trash by calling delete().

BoxFile file = new BoxFile(api, "id");
List<BoxFileVersion> versions = file.getVersions();
BoxFileVersion firstVersion = versions.get(0);
firstVersion.delete();

Create a versioning of a large File by uploading its content in chunks

An upload session can be created with the createUploadSession(fileSize) method to upload new version of a large file in chunks.

BoxFile file = new BoxFile(api, "id");
BoxFileUploadSession.Info session = file.createUploadSession(fileSize);

//Get the session resource from the session info
BoxFileUploadSession session = sessionInfo.getResource();

//Create the Message Digest for the whole file
MessageDigest digest = null;
try {
    digest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException ae) {
    throw new BoxAPIException("Digest algorithm not found", ae);
}

Once the upload session is created, the large file can be uploaded in chuncks with the uploadPart(partId, stream, offset, partSize, totalSizeOfFile) method of the session instance. If there is a failure in uploading any of the parts, the failed part can be uploaded again without affecting the other parts.

//Reading a large file
FileInputStream fis = new FileInputStream("My_Large_File.txt");
//Create the digest input stream to calculate the digest for the whole file.
DigestInputStream dis = new DigestInputStream(fis, digest);

List<BoxFileUploadSessionPart> parts = new ArrayList<BoxFileUploadSessionPart>();

//Get the part size. Each uploaded part should match the part size returned as part of the upload session.
//The last part of the file can be less than part size if the remaining bytes of the last part is less than
//the given part size
long partSize = sessionInfo.getPartSize();
//Start byte of the part
long offset = 0;
//Overall of bytes processed so far
long processed = 0;
while (processed < fileSize) {
    long diff = fileSize - processed;
    //The size last part of the file can be lesser than the part size.
    if (diff < partSize) {
        partSize = diff;
    }

    //Generate a unique partId
    String partId = LargeFileUpload.generateHex();
    //Upload a part. It can be uploaded asynchorously
    BoxFileUploadSessionPart part = session.uploadPart(partId, dis, offset, partSize, fileSize);
    parts.add(part);

    //Increase the offset and proceesed bytes to calculate the Content-Range header.
    processed += partSize;
    offset += partSize;
}

At any point in time, the list of parts that are being uploaded successfully can be retrivied with the listParts(offset, limit) method of the session instance.

//The following snippet retrives first 1000 parts that are uploaded. Both can be modified based on the needs.
BoxFileUploadSessionPartList partList = session.listParts(0, 1000);
List<BoxFileUploadSessionPart> parts = partList.getEntries();

Once all the parts are uploaded successfully. the upload session can be commited with the commit(digest, parts, attributes, ifMatch, ifNoneMatch) method.

//Creates the file hash
byte[] digestBytes = digest.digest();
//Base64 encoding of the hash
String digestStr = Base64.encode(digestBytes);

//Commit the upload session. If there is a failure, abort the commit.
BoxFile.Info fileInfo = session.commit(digestStr, parts, null, null, null);

The upload session can be aborted at any time with the abort() method of the session instance.

session.abort();

The upload session status can be retrived at any time with the getstatus() method. This call will update the parts processed and other information in the session info instance.

BoxFileUploadSession.Info sessionInfo = session.getStatus();

Create new version of a large File

New versions of a large file can be uploaded with the uploadLargeFile(InputStream, fileSize) method.

File myFile = new File("My File.txt");
FileInputStream stream = new FileInputStream(myFile);

BoxFile file = new BoxFile(api, "id");
BoxFile.Info versionedFileInfo = file.uploadLargeFile(inputStream, myFile.length());

Lock a File

A file can be locked by calling lock(Date).

BoxFile file = new BoxFile(api, "id");
Date expiresAt = new Date();
file.lock(expiresAt);

Unlock a File

A file can be unlocked by calling unlock().

BoxFile file = new BoxFile(api, "id");
file.unlock();

Create a Shared Link

A shared link for a file can be generated by calling createSharedLink(BoxSharedLink.Access, Date, BoxSharedLink.Permissions).

BoxFile file = new BoxFile(api, "id");
BoxSharedLink.Permissions permissions = new BoxSharedLink.Permissions();
permissions.setCanDownload(true);
permissions.setCanPreview(true);
Date unshareDate = new Date();
BoxSharedLink sharedLink = file.createSharedLink(BoxSharedLink.Access.OPEN, unshareDate, permissions);

Get an Embed Link

A file embed link can be generated by calling getPreviewLink().

BoxFile file = new BoxFile(api, "id");
URL embedLink = file.getPreviewLink();

Get Thumbnail

A thumbnail for a file can be retrieved by calling getThumbnail(BoxFile.ThumbnailFileType, int, int, int).

BoxFile file = new BoxFile(api, "id");
byte[] thumbnail = file.getThumbnail(BoxFile.ThumbnailFileType.PNG, 256, 256, 256, 256)

Create Metadata

Metadata can be created on a file by calling createMetadata(Metadata), createMetadata(String, Metadata), or createMetadata(String, String, Metadata)

BoxFile file = new BoxFile(api, "id");
file.createMetadata(new Metadata().add("/foo", "bar"));

Get Metadata

Retrieve a files Metadata by calling getMetadata(), getMetadata(String), or getMetadata(String, String).

BoxFile file = new BoxFile(api, "id");
file.getMetadata();

Update Metadata

Update a files Metadata by calling updateMetadata(Metadata).

BoxFile file = new BoxFile(api, "id");
file.updateMetadata(new Metadata().add("/foo", "bar"));

Delete Metadata

A files Metadata can be deleted by calling deleteMetadata(), deleteMetadata(String), or deleteMetadata(String, String).

BoxFile file = new BoxFile(api, "id");
file.deleteMetadata();

Get All Metadata on File

getAllMetadata(String...) method will return an iterable that will page through all of the metadata associated with the file.

BoxFile file = new BoxFile(api, "id");
Iterable<Metadata> metadataList = file.getAllMetadata("name", "description");
for (Metadata metadata : metadataList) {
    // Do something with the metadata.
}