gitlab4j-api icon indicating copy to clipboard operation
gitlab4j-api copied to clipboard

How can I download an LFS file through the GitLab API?

Open nice-jiang opened this issue 1 month ago • 2 comments

How can I download an LFS file through the GitLab API?

My GitLab version is gitlab/gitlab-ce:15.11.13-ce.0.

The version of gitlab4j-api I am using is:

<dependency>
    <groupId>org.gitlab4j</groupId>
    <artifactId>gitlab4j-api</artifactId>
    <version>5.6.0</version>
</dependency>

Please provide a Java code example.

I have tried using .getRepositoryFileApi().getRawFile(), but I keep getting a pointer file (e.g., version https://git-lfs.github.com/spec/v1 ...) instead of the actual file content.

nice-jiang avatar Nov 28 '25 10:11 nice-jiang

This library is just a way to perform REST calls... if the gitlab backend is returning a link to the object then this is what you will get with the corresponding method in the java client.

Or maybe I didn't understood your question correctly?

jmini avatar Dec 09 '25 05:12 jmini

This library is just a way to perform REST calls... if the gitlab backend is returning a link to the object then this is what you will get with the corresponding method in the java client.

Or maybe I didn't understood your question correctly?

Thank you, I have already solved this problem. I did not use the gitlab4j-api to download the file. Instead, I found the actual file download link and then used a REST call to fetch its content.

Below is my own example, which can serve as a reference for others.

String authToken = gitLabApi.getAuthToken();
String downloadUrl = projectHttpRepoUrl + "/gitlab-lfs/objects/" + oid;
java.net.URL url = new java.net.URL(downloadUrl);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");
if (authToken != null && !authToken.isEmpty()) {
    String encodedAuth = java.util.Base64.getEncoder().encodeToString(("oauth2:" + authToken).getBytes());
    connection.setRequestProperty("Authorization", "Basic " + encodedAuth);
}

int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    throw new Exception("LFS file download fail,code: " + responseCode);
}
return connection.getInputStream();

projectHttpRepoUrl projectHttpRepoUrl is the git clone address. oid is to get a string in the pointer file. pointer file content like this oid value without 'oid sha256:'

version https://git-lfs.github.com/spec/v1
oid sha256:f8e3086f3cea0fb3fefb29937ab5ed9d1967079633960ccbxxxxxxx50e76153effc98
size 1261371392

nice-jiang avatar Dec 10 '25 07:12 nice-jiang