java - 如何从 google webapp 引擎下载图像文件?

标签 java image google-app-engine servlets download

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.setContentLength(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();

如何修复整个代码以下载图像文件?因为如果我使用数字 1,它会出错,显示“错误 6 (net::ERR_FILE_NOT_FOUND):找不到文件或目录。”,或者如果我使用数字 2,它看起来不错,但是存储的文件类型为字节码,即不是图像文件。

谁能给我任何想法或例子?

最佳答案

不久前我遇到了这个问题。您无法读取使用该应用程序上传的文件。它们被视为静态应用程序 blob,并且不以任何方式可供您的代码访问。

看看here请注意,现在唯一可用的选项是 BLOBSTORE。 如果您希望应用程序代码可以读取某些内容,则必须将其存储在 Blobstore 中或作为数据存储中对象上的 BlobProperty 存储(这是非常低效的,如果可以的话请使用 Blobstore)。

关于java - 如何从 google webapp 引擎下载图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7369646/

相关文章:

google-app-engine - 我可以从 Google 应用程序引擎向 Google Hangouts 用户发送消息吗?

java - 获取一个知道其名称的按钮

java - 400 错误请求 [Content-Length : 0, Chunked: false]

java - 如何在java中转换巨大的xml文件?

python - 使用 PIL 裁剪图像时如何设置坐标?

java - Google App Engine(Java) 数据库自动生成的 ID

Java 8 - 使用 Comparator 以不同顺序比较多个字段

python - PIL : How to reopen an image after verifying?

c++ - 使用 C++ 从多个网络摄像头捕获图片

java - 如何修复 "java.lang.NoClassDefFoundError: com/google/api/client/http/HttpRequestInitializer"运行时错误?