How do I download a image file from google webapp engine?
AppEngineFile AFE = new AppEngineFile(FILESYSTEM + alist.get(0).getPath());
BlobKey bk = FileServiceFactory.getFileService().getBlobKey(AFE);
if("image/jpeg".equals(alist.get(0).getContentType()) ){
resp.setContentType("image/jpeg");
}
resp.setHeader("Content-Disposition", "attachment; filename=\"" + alist.get(0).getTitle() + "\"");
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = null;
try {
file = fileService.getBlobFile(bk);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileReadChannel ch = null;
try {
ch = fileService.openReadChannel(file, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (LockException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] barray = new byte[MAXSIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ByteBuffer bb = ByteBuffer.wrap(barray);
int nRead;
while ((nRead=ch.read(bb)) != -1) {
for (int i=0; i < nRead; i++) {
try {
baos.write(barray[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
bb.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
resp.setCon开发者_开发百科tentLength(baos.size());
// resp.getOutputStream().write(baos.toByteArray()); // <= if I use it, this message, "Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.", is showed.
// out.print(baos); // <= if I use this, I can download a file but it is byte code.
baos.flush();
baos.close();
How do I fix whole this code for downloading an image file? because If I use Number 1, it make a error, which is "Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.", is showed." or if i use number 2, it looks fine but the type of stored file is byte code. This means is not image file.
Who can give me any idea or example?
I ran into this problem a while back. You cannot read files uploaded with the application. They are considered static application blobs and do not exist in any way accessible to your code.
Take a look here and notice that the only available option right now is BLOBSTORE
.
If you want something to be readable by application code, it must be stored in the Blobstore or as a BlobProperty
on an object in the Datastore (which is very inefficient, use the Blobstore if you can).
精彩评论