I am developing a Java - JSF web application in which I am showing a pop-up in order to let the user choose a document from Google Drive to download it.
To do that, I have some js code:
<script src="filepicker.js"></script>
<script>
function initPicker() {
var picker = new FilePicker({
apiKey: 'MY_API_KEY',
clientId: my_client_id,
buttonEl: document.getElementById('pick'),
onSelect : function(file) {
if (file.id) {
sendLinkToBean(file.id);
} else {
alert('Unable to download file.');
}
}
});
}
</script>
<a4j:jsFunction name="sendLinkToBean" action="#{gPPersonFormBean.downloadFile()}">
<a4j:param name="param1" assignTo="#{gPPersonFormBean.fileId}"/>
</a4j:jsFunction>
The file.id arrives the Bean and I try to get it as shown in G.Drive's API:
public void downloadFile(){
try {
Drive driveService = getDriveService();
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId) .executeMediaAndDownloadTo(outputStream);
} catch (IOException e) {
String mess = "downloadFile(): "
+ (e.getMessage()!=null?". "+e.getMessage():"")
+ (e.getCause()!=null?". "+e.getCause():"");
logger.error(mess);
}
}
But I get FileNotFoundException:
com.google.api.client.http.HttpResponseException: 404 Not Found
{
"error": {"theID"
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "File not found: 1tvnGWDCse4TFQwIvqEDTlvv2cebfs0C2JBtjTP5A42I.",
"locationType": "parameter",
"location": "fileId"
}
],
"code": 404,
"message": "File not found: theID."
}
}
Does anyone know why this might be happening? Thanks in advance.
EDIT: I have just compared the id received with the one given by Google with the file's link and they are exactly the same.
EDIT 2: If I do driveService.files().list();
it returns an empty list.
As Tanaike said I had to use export instead of get but also executeAndDownloadTo instead of executeMediaAndDownloadTo
So it worked being:
String fileId = "## file ID ##";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
.executeAndDownloadTo(outputStream);