File Upload google app engine blobstore
-
25-10-2019 - |
Question
I am going to use Google app engine Blobstore to store my uploaded files. File type can be anything (.txt,.pdf,.docx etc) I have written following servlet to download stored files in Google app engine Blobstore.
public class Serve extends HttpServlet {
private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
blobstoreService.serve(blobKey, res);
}
}
But every time I request a file by giving a url as below, http://127.0.0.1:8888/serve?blob-key=DEHQ3U_2wtUdEL7XPI434Q file is downloaded nicely. But no extension for file. And name of the file is always ‘serve’ What should I do to download the uploaded file with the original name of the file? Thanks,
Solution
I know python has a send_as
option that automatically sets the filename for the response, but I think in Java you will have to add a Content-Disposition
header to the response like:
Content-Disposition: attachment; filename=your-file.docx;
The BlobInfo for your blob keeps the original filename and you can fetch it via getFilename
OTHER TIPS
I used the following code to serve a blob by passing the blob-key as a String to my Serve.java . File is downloaded using the original filename as well as the original extension. Found a more detailed discussion at http://onjava.com/onjava/excerpt/jebp_3/index3.html
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
BlobInfoFactory bi = new BlobInfoFactory();
BlobKey blobKey = new BlobKey(req.getParameter("blob-key"));
String fname = bi.loadBlobInfo(blobKey).getFilename();
res.setContentType("application/x-download");
res.setHeader("Content-Disposition", "attachment; filename=" + fname);
blobstoreService.serve(blobKey, res);