blobStoreService.serve()没有提供下载文件

时间:2012-08-11 07:08:02

标签: java google-app-engine blobstore

我有一个servlet,我首先从http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf下载pdf,然后在我的blobstore上传内容,当用户在浏览器中发送get请求时,blob将在浏览器中下载,而不是下载它以其他格式显示数据。这是我的servlet代码:

package org.ritesh;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;

import javax.servlet.http.*;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileWriteChannel;

@SuppressWarnings("serial")
public class BlobURLServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/plain");
        resp.getWriter().println("Hello, world");

         FileService fileService = FileServiceFactory.getFileService();

          // Create a new Blob file with mime-type "text/plain"

          String url="http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf";
          URL url1=new URL(url);
          HttpURLConnection conn=(HttpURLConnection) url1.openConnection();
          String content_type=conn.getContentType();
          InputStream stream =conn.getInputStream();
          AppEngineFile file = fileService.createNewBlobFile("application/pdf");
          file=new AppEngineFile(file.getFullPath());
         Boolean lock = true;
          FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

          // This time we write to the channel directly
          String s1="";
          String s2="";

          byte[] bytes = IOUtils.toByteArray(stream);


          writeChannel.write(ByteBuffer.wrap(bytes));
          writeChannel.closeFinally();
          BlobKey blobKey = fileService.getBlobKey(file);
          BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
          blobStoreService.serve(blobKey, resp);


    }
}

我在onemoredemo1.appspot.com上部署了这个servlet。请打开此URL并注意当您单击BlobURL servlet时它显示内容而不是显示下载对话框。我应该在代码中进行哪些修改,以便在浏览器中显示下载对话框?

1 个答案:

答案 0 :(得分:1)

看这里:

resp.setContentType("text/plain");

你说的内容是纯文本,但事实并非如此。您需要将Content-Disposition标头适当地设置为附件,并将内容类型设置为application/pdf

此外,如果您要提供二进制内容,则不应 使用编写器(您正在编写"Hello, world")。

如果您将前几行更改为:

resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=sample.pdf");

你可能会发现这就是所需要的。