0

I have been trying to upload a pdf file on Google Cloud Storage using my application but I am unable to do so.I have searched the net and found the below given code but the problem is that this code is useful in uploading txt file but not pdf file.When I try to upload pdf file it uploads successfully but when I try to open it it doesn't open.I am using the following code:

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
RequestDispatcher rd=req.getRequestDispatcher("career-registration-successfull.jsp");
RequestDispatcher rd1=req.getRequestDispatcher("career-registration-failed.jsp");
String name="";
String email="";
long whatsapp=0;
long number=0;
String query="";
int flag1=0;
int flag2=0;
isMultipart = ServletFileUpload.isMultipartContent(req);
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter( );
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Subhanshu Bigasia\\Desktop\\Amazon.pdf");
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket=storage.get(("combucket1eduvitae7"));
ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
String targetFileStr="";
try {
    List<FileItem>  fileName = sfu.parseRequest(req);
     for(FileItem f:fileName)
        {
        try {
            f.write (new File("C:\\Users\\Subhanshu Bigasia\\Desktop\\Afcat.pdf"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //targetFileStr = readFile("/Users/tkmajdt/Documents/workspace/File1POC1/" + f.getName(),Charset.defaultCharset());
        targetFileStr = new String(Files.readAllBytes(Paths.get("C:\\Users\\Subhanshu Bigasia\\Desktop\\Afcat.pdf")));
        }
}
catch(Exception e) {
    e.printStackTrace();
}
BlobId blobId = BlobId.of("combucket1eduvitae", "my_blob_name1");
//Blob blob = bucket.create("my_blob_name1", targetFileStr.getBytes(), "text/plain");
Blob blob=bucket.create("myblob",fileInputStream, "text");

Can someone help in solving this problem.
Thank You in Advance

Maxim
  • 4,075
  • 1
  • 14
  • 23
user10136991
  • 63
  • 1
  • 10

2 Answers2

2

I solved the problem by using the below code:

String name="";
String email="";
long whatsapp=0;
long number=0;
String query="";
int flag1=0;
int flag2=0;
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter( );
    if( !isMultipart ) {
   out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet upload</title>");  
   out.println("</head>");
   out.println("<body>");
   out.println("<p>No file uploaded</p>"); 
   out.println("</body>");
   out.println("</html>");
   return;
}

DiskFileItemFactory factory = new DiskFileItemFactory();

// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );

try { 
   // Parse the request to get file items.
   List fileItems = upload.parseRequest(req);

   // Process the uploaded file items
   Iterator i = fileItems.iterator();

   out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet upload</title>");  
   out.println("</head>");
   out.println("<body>");

   while ( i.hasNext () ) {
      FileItem fi = (FileItem)i.next();
      if ( !fi.isFormField () ) {
         // Get the uploaded file parameters
        try { String fieldName = fi.getFieldName();
         String fileName = fi.getName();
         String contentType = fi.getContentType();
         boolean isInMemory = fi.isInMemory();
         long sizeInBytes = fi.getSize();
         Date date=new Date();             
         System.out.println(("Uploaded Filename: " + fileName + "<br>"));
         flag1=1;
         File f1=new File("C:\\Users\\Subhanshu Bigasia\\Desktop\\amazon2.pdf");
         FileInputStream fileInputStream = (FileInputStream) fi.getInputStream();
         Storage storage = StorageOptions.getDefaultInstance().getService();
         Bucket bucket=storage.get(("combucket1eduvitae7"));
         ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
         BlobId blobId = BlobId.of("combucket1eduvitae", "my_blob_name1");
         //Blob blob = bucket.create("my_blob_name1", targetFileStr.getBytes(), "application/pdf");
         Blob blob=bucket.create(fileName+" "+date.toString(),fileInputStream,"application/pdf");
         flag1=1;
        }
        catch(Exception e) {
            flag1=0;
            e.printStackTrace();
        }
      }

Notice that I have used
Blob blob=bucket.create(fileName+" "+date.toString(),fileInputStream,"application/pdf"); instead of
Blob blob=bucket.create(fileName+" "+date.toString(),fileInputStream,"text/plain");

user10136991
  • 63
  • 1
  • 10
0

First follow the Cloud Storage Client Libraries for Java documentation which will get you started.

Than you can try this example for uploading files to Cloud Storage bucket using Java (found here):

/**
   * Uploads data to an object in a bucket.
   *
   * @param name the name of the destination object.
   * @param contentType the MIME type of the data.
   * @param file the file to upload.
   * @param bucketName the name of the bucket to create the object in.
   */
  public static void uploadFile(
      String name, String contentType, File file, String bucketName)
      throws IOException, GeneralSecurityException {
    InputStreamContent contentStream = new InputStreamContent(
        contentType, new FileInputStream(file));
    // Setting the length improves upload performance
    contentStream.setLength(file.length());
    StorageObject objectMetadata = new StorageObject()
        // Set the destination object name
        .setName(name)
        // Set the access control list to publicly read-only
        .setAcl(Arrays.asList(
            new ObjectAccessControl().setEntity("allUsers").setRole("READER")));

    // Do the insert
    Storage client = StorageFactory.getService();
    Storage.Objects.Insert insertRequest = client.objects().insert(
        bucketName, objectMetadata, contentStream);

    insertRequest.execute();
  }

You can find easy to follow getting started tutorial in the GitHub repository here. Please take a look at Stack Overflow thread Upload image to Google Cloud Storage (Java) as well.

komarkovich
  • 2,223
  • 10
  • 20