Skip to content

Instantly share code, notes, and snippets.

@pmedcraft
Last active August 12, 2019 16:26
Show Gist options
  • Save pmedcraft/880906cfe7da74280e0609c8f053d8c8 to your computer and use it in GitHub Desktop.
Save pmedcraft/880906cfe7da74280e0609c8f053d8c8 to your computer and use it in GitHub Desktop.
Uploads a collection of files to SDL WorldServer using the REST API returning a list of FileUploadResponse objects containing data from each uploaded asset
public class FileUploadResponse {
private String name;
private String internalName;
private String fullName;
private String url;
private double size;
private long creationTime;
private boolean exists;
private File[] files;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInternalName() {
return internalName;
}
public void setInternalName(String internalName) {
this.internalName = internalName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public long getCreationTime() {
return creationTime;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public boolean isExists() {
return exists;
}
public void setExists(boolean exists) {
this.exists = exists;
}
public File[] getFiles() {
return files;
}
public void setFiles(File[] files) {
this.files = files;
}
}
public static List<FileUploadResponse> uploadAssets(String wsBaseUrl, String token, Collection<File> files)
throws IOException, URISyntaxException {
List<FileUploadResponse> fileUploadResponses = new ArrayList<>();
for (File file : files) {
String boundary = "--" + UUID.randomUUID() + "--";
URI postUri = new URIBuilder(wsBaseUrl + "/ws-api/v1/files")
.addParameter("token", token)
.addParameter("content-type", "multipart/form-data; boundary=" + boundary)
.build();
MultipartEntityBuilder builder = MultipartEntityBuilder
.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setBoundary(boundary)
.addPart("file", new FileBody(file));
HttpPost httpPost = new HttpPost(postUri);
httpPost.setEntity(builder.build());
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(httpPost);
Gson gson = new GsonBuilder().create();
FileUploadResponse fileUploadResp = gson
.fromJson(new InputStreamReader(response.getEntity().getContent()), FileUploadResponse.class);
fileUploadResponses.add(fileUploadResp);
}
return fileUploadResponses;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment