2

用户上传了一些文件,我存储在 Google Cloud Storage 中。现在用户回来了,想从我的应用程序显示的列表中下载文件。他/她单击链接并调用 servlet。该 servlet 背后的代码是什么样的?另外,我不想公开这些对象。这是我的样子:有没有更简单的方法来做到这一点?谢谢。

public class ServeGSObject extends HttpServlet {
    FileService fileService = FileServiceFactory.getFileService();
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        String fullFilePath = request.getParameter("objectPath");
        AppEngineFile file = new AppEngineFile(fullFilePath);
        try {
            FileReadChannel channel = fileService.openReadChannel(file, false);
            BufferedInputStream bis = new BufferedInputStream(Channels.newInputStream(channel));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            response.setHeader("Content-Disposition", "inline;filename=\"" + file.getNamePart() + "");
            int b = 0;
            while((b = bis.read()) != -1) {
                bos.write(b);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4

1 回答 1

1

您可以使用生成blobKey与您的 Google Storage 文件对应的临时文件blobstoreService.createGsBlobKey

并使用https://developers.google.com/appengine/docs/java/blobstore/overview#Serving_a_Blob像常规 blobstore 文件一样提供它blobstoreService.serve(blobKey, res)

于 2012-05-10T10:36:26.390 回答