简体   繁体   English

如何使用Java在Google Cloud Storage中插入pdf文件

[英]How to insert a pdf file in Google Cloud Storage using Java

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: 我一直在尝试使用我的应用程序将pdf文件上传到Google云端存储,但我无法这样做。我已经在网上搜索了以下给出的代码,但问题是该代码对于上传txt文件很有用,但不能pdf文件。当我尝试上传pdf文件时,它成功上传,但是当我尝试打开它时,它没有打开。我正在使用以下代码:

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 先感谢您

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"); Blob blob = bucket.create(fileName +“” + date.toString(),fileInputStream,“ application / pdf”); instead of 代替
Blob blob=bucket.create(fileName+" "+date.toString(),fileInputStream,"text/plain"); Blob blob = bucket.create(fileName +“” + date.toString(),fileInputStream,“ text / plain”);

First follow the Cloud Storage Client Libraries for Java documentation which will get you started. 首先,遵循JavaCloud Storage Client Libraries文档 ,这将帮助您入门。

Than you can try this example for uploading files to Cloud Storage bucket using Java ( found here ): 比您可以尝试使用Java( 在此处找到 )将文件上传到Cloud Storage存储桶的示例:

/**
   * 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 . 你可以找到易于遵循入门教程在GitHub的仓库在这里 Please take a look at Stack Overflow thread Upload image to Google Cloud Storage (Java) as well. 请查看堆栈溢出线程, 还将图像上传到Google Cloud Storage(Java)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java API更新Google Cloud Storage中文件的ACL - How to update ACL of a file in Google Cloud Storage using Java API 如何使用java上传谷歌云存储中的文件 - How to upload a file in the google cloud storage using java Google Cloud Storage使用Java上传文件 - Google Cloud Storage upload a file using java 如何从 JAVA 中的谷歌存储云存储桶中获取所有 pdf 文件 - How to get all pdf file from google storage cloud bucket in JAVA 使用 JSON API 和 Java 在 Google Cloud Storage 中插入对象(作为文件夹) - Insert object (as a folder) in Google Cloud Storage using JSON API with Java 使用谷歌云存储与 java - Using google cloud storage with java 是否可以使用 java 更改谷歌云存储文件的文件名? - Is it possible to change the filename of a google cloud storage file using java? 如何使用Java API将超过32Mb的文件上传到谷歌云存储 - How to upload a file more that 32Mb to google cloud storage using Java API 如何使用Java App Engine正确上传(映像)文件到Google云端存储? - How to properly upload (image) file to Google Cloud Storage using Java App Engine? 我如何使用BlobstoreService Java在Google云存储中下载文件 - how can i download a file in google cloud storage using BlobstoreService java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM