Search code examples
javagoogle-app-enginejakarta-eeapache-commons

uploading a file using apache streaming API and Google App Engine Virtual File System


To upload a file into my project directory which is there on the google appengine,I am trying to use apache streaming API and Google App Engine Virtual File System. Here is what I have been able to do till now :

    String path = request.getParameter("Data");
    PrintWriter writer = response.getWriter();
     try {
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if( !isMultipart ) {
           writer.println("File cannot be uploaded !");
       }
       else {
           ServletFileUpload upload = new ServletFileUpload();
           FileItemIterator iter = upload.getItemIterator(request);
           List list = null;
           while(iter.hasNext()) {
               FileItemStream item = iter.next();
               String name  = item.getFieldName();
               String fileName = item.getName();
               InputStream stream = item.openStream();
               if(item.isFormField()) {
                   // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
               } else {
                   GaeVFS.setRootPath( getServletContext().getRealPath("/") );
                   FileSystemManager fsManager = GaeVFS.getManager();
                   //....NOW WHAT....

               }
           }
       }

I am stuck there in the else block. How to proceed now ? I have to write the file to a directory named uploads in my project.


Solution

  • GAE filesystem is read-only. There is no write access via an API. The only way to change filesystem contents is to update the app via appcfg.

    If you need to upload data and store it use Blobstore or Google Cloud Storage.

    Upload to blobstore:

    String path = request.getParameter("Data");
    PrintWriter writer = response.getWriter();
     try {
       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
       if( !isMultipart ) {
           writer.println("File cannot be uploaded !");
       }
       else {
           ServletFileUpload upload = new ServletFileUpload();
           FileItemIterator iter = upload.getItemIterator(request);
           List list = null;
           while(iter.hasNext()) {
               FileItemStream item = iter.next();
               String name  = item.getFieldName();
               String fileName = item.getName();
               InputStream stream = item.openStream();
               if(item.isFormField()) {
                   // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
               } else {
    
                // Get a file service
                FileService fileService = FileServiceFactory.getFileService();
    
                // Create a new Blob file with mime-type "text/plain"
                AppEngineFile file = fileService.createNewBlobFile(mimeType, filename);
    
                // Open a channel to write to it
                boolean lock = true;
                FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
    
                // copy byte stream from request to channel
                byte[] buffer = new byte[10000];
                int len;
                while ((len = stream.read(buffer)) > 0) {
                    writeChannel.write(ByteBuffer.wrap(buffer, 0, len));
                }
    
                writeChannel.closeFinally();
    
                // here your data is saved to blobstore
                // you should now save a blobstore key somewhere (=to a datastore)
                // so that you can find it next time
                String blobKey = fileService.getBlobKey(file).getKeyString();
    
               }
           }
       }
    

    Serving a blob:

    public class BlobServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String blobParameter = request.getParameter("blob-key");
        if (blobParameter == null) {
            response.sendError(404, "Missing 'blob-key' parameter.");
        }
    
        BlobKey blobKey = new BlobKey(blobParameter);
    
        response.setHeader("Cache-Control", "max-age=" + (15 * 60));   // 15 min
        BlobstoreServiceFactory.getBlobstoreService().serve(blobKey, response);
    }
    }
    

    Registering your servlet:

    <servlet>
        <servlet-name>BlobServlet</servlet-name>
        <servlet-class>com.yourpackage.BlobServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BlobServlet</servlet-name>
        <url-pattern>/blobservet</url-pattern>
    </servlet-mapping> 
    

    Referencing blob in your JSP:

    <a src="/blobserve?<%=blobKey%>">Link to blob</a>