0

我有一个 servlet,我首先从http://www.cbwe.gov.in/htmleditor1/pdf/sample.pdf下载一个 pdf,将其内容上传到我的 blobstore,当用户在浏览器中发送获取请求时,一个 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 时它正在显示内容而不是显示下载对话框。我应该在我的代码中进行哪些修改,以便在浏览器中显示下载对话框?

4

1 回答 1

1

看这里:

resp.setContentType("text/plain");

您说过内容是纯文本,但实际上不是。您需要将Content-Disposition标题适当地设置为附件,并将内容类型设置为application/pdf.

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

如果您将前几行更改为:

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

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

于 2012-08-11T07:13:27.467 回答