0

私は最初にhttp://www.cbwe.gov.in/htmleditor1/pdf/sample.pdfから pdf をダウンロードするサーブレットを持っています。そのコンテンツは私のブロブストアにアップロードされ、ユーザーがブラウザーで取得要求を送信すると、ブロブブラウザでダウンロードされますが、ダウンロードする代わりに、他の形式でデータを表示しています。これが私のサーブレットのコードです:

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 にデプロイします。この URL を開いて、BlobURL サーブレットをクリックすると、ダウンロード ダイアログではなくコンテンツが表示されることに注意してください。ブラウザーにダウンロード ダイアログが表示されるようにするには、コードをどのように変更すればよいですか?

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 に答える