gpt4 book ai didi

java - blobStoreService.serve() 不提供下载文件

转载 作者:行者123 更新时间:2023-12-01 15:13:55 29 4
gpt4 key购买 nike

我有一个 servlet,我首先在其中下载 pdf http://www.cbwe.gov.in/htmleditor1/pdf/sample.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 时,它显示内容而不是显示下载对话框。我应该在代码中进行哪些修改才能在浏览器中显示下载对话框?

最佳答案

看这里:

resp.setContentType("text/plain");

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

此外,如果您要提供二进制内容,您不应该使用编写器(您正在使用编写器编写“Hello,world”) .

如果您将前几行更改为:

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

您可能会发现这就是所需要的全部。

关于java - blobStoreService.serve() 不提供下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11912759/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com