Java blobStoreService.service()未提供下载文件
我有一个servlet,在这个servlet中,我首先从我的blobstore上传内容下载pdf,当用户在浏览器中发送get请求时,blob将在浏览器中下载,但不是下载,而是以其他格式显示数据。以下是我的servlet代码:Java blobStoreService.service()未提供下载文件,java,google-app-engine,blobstore,Java,Google App Engine,Blobstore,我有一个servlet,在这个servlet中,我首先从我的blobstore上传内容下载pdf,当用户在浏览器中发送get请求时,blob将在浏览器中下载,但不是下载,而是以其他格式显示数据。以下是我的servlet代码: package org.ritesh; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; impo
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
标题适当地设置为附件,并将内容类型设置为application/pdf
此外,如果要提供二进制内容,则不应同时使用writer(您正在使用它编写“Hello,world”
)
如果将前几行更改为:
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "attachment;filename=sample.pdf");
你可能会发现这就是所需要的