I have a java servlet that serves files from s3. These files can be either image, pdf or doc/docx. I have to implement a feature in my web application to display these files in google doc viewer.
In my case, I am not able to send content so that google doc viewer reads it and displays the file. (when shouldDownload == Binary.YES).
This the code I have that downloads the file from s3 and set it in my bean class -
ApplicantzFileModel document = (ApplicantzFileModel) MongoSelectRogueModel
.selectOneById(ApplicantzFileModel.class, id);
Binary shouldDownload = Binary.valueOf(download);
if (document != null) {
if (shouldDownload == Binary.YES) {
docBean.fileStream = document.downloadFileStream();
docBean.fileName = document.getFileName();
docBean.isFileDownloadResponse = true;
} else {
File file = document.downloadFile();
if (file != null) {
String content = null;
content = FileHandler.read(file);
if (content != null) {
docBean.fileContent = content;
docBean.fileName = document.getFileName();
}
}
}
docBean.actionSuccess = true;
docBean.isFileContentResponse = true;
}
This is the code in my doGet/doPost to serve the response -
if (bean.isFileDownloadResponse) {
OutputStream responseOutputStream;
try {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "inline; filename=" + bean.fileName);
responseOutputStream = response.getOutputStream();
byte[] buf = new byte[4096];
int len = -1;
while ((len = bean.fileStream.read(buf)) != -1) {
responseOutputStream.write(buf, 0, len);
}
responseOutputStream.flush();
responseOutputStream.close();
bean.fileStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
response.setContentType("application/msword");
response.addHeader("Content-disposition", "inline; filename=" + bean.fileName);
responseStr = bean.fileContent;
PrintWriter writer = null;
try {
writer = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
if (writer != null) {
writer.println(responseStr);
writer.flush();
writer.close();
}
}
And this is the html code in my frontend to open google doc viewer in fancybox -
"<a data-fancybox="" data-type="iframe" data-src="http://docs.google.com/viewer?url=http%3A%2F%2Fsomeserver.com%2Fapplication%2Fdocument%3Faction%3Dget%26id%3Dsomeid%26download%3DYES&embedded=true" href="javascript:void(0);" data-doc-id="someid">My Link</a>"
Or more specifically, google doc viewer url that opens up -
var innerurl = encodeURIComponent('http://someserver.com/application/document?action=get&id='+this.docId+'&download=YES');
this.docUrl = 'http://docs.google.com/viewer?url='+innerurl+'&embedded=true';
I am not able to open the word or pdf document in my fancybox. Can someone please suggest what to do to serve files via Java.